Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement object type spread (both $Exact and nonexact semantics) #1

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
- `interface Stuff {}` - Interfaces
- `class Thing {}` - Class Declarations
- `import type {Alias} from "./other";` Type imports
- `...Other` and `...$Exact<Other>` - Object type spreads

**Unsupported:**

Expand Down
23 changes: 13 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,19 @@
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-jest": "^20.0.3",
"babel-plugin-tester": "^3.0.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-preset-env": "^1.4.0",
"babel-preset-env": "^1.5.2",
"babel-preset-flow": "^6.23.0",
"flow-bin": "^0.46.0",
"flow-bin": "^0.47.0",
"flow-coverage-report": "^0.3.0",
"husky": "^0.13.3",
"jest": "^20.0.3",
"lint-staged": "^3.4.2",
"prettier": "^1.3.1",
"husky": "^0.13.4",
"jest": "^20.0.4",
"jest-environment-node-debug": "^2.0.0",
"lint-staged": "^3.6.0",
"prettier": "^1.4.4",
"strip-indent": "^2.0.0"
},
"lint-staged": {
Expand All @@ -47,14 +50,14 @@
"coverageDirectory": "coverage/jest"
},
"dependencies": {
"babel-errors": "^1.1.0",
"babel-errors": "^1.1.1",
"babel-explode-module": "^2.0.0",
"babel-file-loader": "^1.0.1",
"babel-file-loader": "^1.0.2",
"babel-flow-identifiers": "^1.1.2",
"babel-flow-scope": "^1.2.0",
"babel-helper-simplify-module": "^2.2.0",
"babel-log": "^1.0.3",
"babel-log": "^2.0.0",
"babel-react-components": "^1.0.1",
"babel-types": "^6.24.1"
"babel-types": "^6.25.0"
}
}
101 changes: 101 additions & 0 deletions src/__tests__/classes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,107 @@ pluginTester({
},
tests: stripIndents([
// prop types
{
title: 'object type spread',
code: `
type C = {
c: any
};
class Foo extends React.Component {
props: {
a: {
b: any,
...C
}
};
}
`,
output: `
import _PropTypes from "prop-types";
type C = {
c: any
};
class Foo extends React.Component {
props: {
a: {
b: any;
...C;
}
};
static propTypes = {
a: _PropTypes.shape({
b: _PropTypes.any.isRequired,
c: _PropTypes.any
}).isRequired
};
}
`,
},
{
title: 'object type spread exact',
code: `
type C = {
c: any
};
class Foo extends React.Component {
props: {
a: {
b: any,
...$Exact<C>
}
};
}
`,
output: `
import _PropTypes from "prop-types";
type C = {
c: any
};
class Foo extends React.Component {
props: {
a: {
b: any;
...$Exact<C>;
}
};
static propTypes = {
a: _PropTypes.shape({
b: _PropTypes.any.isRequired,
c: _PropTypes.any.isRequired
}).isRequired
};
}
`,
},
{
title: 'object type spread exact shorthand',
code: `
type C = {
c: any
};
class Foo extends React.Component {
props: {
a: {| ...C |}
};
}
`,
output: `
import _PropTypes from "prop-types";
type C = {
c: any
};
class Foo extends React.Component {
props: {
a: {| ...C |}
};
static propTypes = {
a: _PropTypes.shape({
c: _PropTypes.any.isRequired
}).isRequired
};
}
`,
},
{
title: 'any',
code: `
Expand Down
42 changes: 37 additions & 5 deletions src/convertTypeToPropTypes.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// @flow
import type {Path, Node} from './types';
import * as t from 'babel-types';
import {log} from 'babel-log';
import {loadImportSync} from 'babel-file-loader';
import matchExported from './matchExported';
import error from './error';
Expand Down Expand Up @@ -64,10 +63,16 @@ function typeToValue(node) {
return t.valueToNode(value);
}

function isExact(path: Path) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about {| ... |}?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is that shorthand for exact?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it should be preferred over $Exact

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return path.node.type === 'GenericTypeAnnotation' &&
(path.node.id.name === '$Exact' || path.context.parentPath.parentPath.node.exact)
}

type Options = {
getPropTypesRef: () => Node,
getPropTypesAllRef: () => Node,
resolveOpts?: Object,
nonExactSpread?: boolean,
};

let refPropTypes = (property: Node, opts: Options): Node => {
Expand Down Expand Up @@ -169,9 +174,16 @@ converters.ObjectTypeAnnotation = function(
let props = [];

for (let property of path.get('properties')) {
props.push(
convert(property, opts, {...context, depth: context.depth + 1}),
);
// result may be from:
// ObjectTypeProperty - objectProperty
// ObjectTypeSpreadProperty - Array<objectProperty>
const converted = convert(property, opts, {...context, depth: context.depth + 1});
if (Array.isArray(converted)){
converted.forEach((prop) => props.push(prop));
}
else {
props.push(converted);
}
}

let object = t.objectExpression(props);
Expand Down Expand Up @@ -203,13 +215,29 @@ converters.ObjectTypeProperty = (

let converted = convert(value, opts, context);

if (!path.node.optional && !converted[OPTIONAL]) {
if (!path.node.optional && !converted[OPTIONAL] && !opts.nonExactSpread) {
converted = t.memberExpression(converted, t.identifier('isRequired'));
}

return t.objectProperty(inheritsComments(keyId, key.node), converted);
};

converters.ObjectTypeSpreadProperty = (
path: Path,
opts: Options,
context: Context,
) => {
const argument = path.get('argument')

// Unless or until the strange default behavior changes in flow (https://github.com/facebook/flow/issues/3214)
// every property from spread becomes optional unless it uses `...$Exact<T>`
// @see also explanation of behavior - https://github.com/facebook/flow/issues/3534#issuecomment-287580240
const converted = convert(argument, {...opts, nonExactSpread: !isExact(argument)}, context);

// @returns flattened properties from shape
return converted.arguments[0].properties;
};

converters.ObjectTypeIndexer = (
path: Path,
opts: Options,
Expand All @@ -235,6 +263,10 @@ let typeParametersConverters = {
convert(param, opts, context),
]);
},
'$Exact': (path: Path, opts: Options, context: Context) => {
let param = path.get('typeParameters').get('params')[0];
return convert(param, opts, context);
},
};

function getTypeParam(path, index) {
Expand Down
1 change: 0 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import * as t from 'babel-types';
import {isReactComponentClass} from 'babel-react-components';
import findPropsClassProperty from './findPropsClassProperty';
import convertTypeToPropTypes from './convertTypeToPropTypes';
import {log} from 'babel-log';

type PluginOptions = {
resolveOpts?: Object,
Expand Down
6 changes: 3 additions & 3 deletions src/matchExported.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @flow
import {explodeModule} from 'babel-explode-module';
import {explodedToStatements} from 'babel-helper-simplify-module';
import {format} from 'babel-log';
import format from 'babel-log';
import * as t from 'babel-types';
import error from './error';

Expand Down Expand Up @@ -41,11 +41,11 @@ export default function matchExported(file: Object, exportName: string) {
} else if (item.node.id) {
id = item.node.id;
} else {
throw error(item, `Unexpected node:\n\n${format(item)}`);
throw error(item, `Unexpected node:\n\n${String(format(item))}`);
}

if (!id) {
throw new Error(`Couldn't find id on node:\n\n${format(item)}`);
throw new Error(`Couldn't find id on node:\n\n${String(format(item))}`);
}

return id.name === local;
Expand Down
Loading