Fix cloneNode with typeAnnotation. (#8997)

Fixes #8996
This commit is contained in:
Greg Bergé 2018-11-13 02:10:09 +01:00 committed by Logan Smyth
parent efa571a42c
commit 4fcee1751a
2 changed files with 22 additions and 0 deletions

View File

@ -37,6 +37,12 @@ export default function cloneNode<T: Object>(node: T, deep: boolean = true): T {
// Special-case identifiers since they are the most cloned nodes. // Special-case identifiers since they are the most cloned nodes.
if (type === "Identifier") { if (type === "Identifier") {
newNode.name = node.name; newNode.name = node.name;
if (has(node, "typeAnnotation")) {
newNode.typeAnnotation = deep
? cloneIfNodeOrArray(node.typeAnnotation, true)
: node.typeAnnotation;
}
} else if (!has(NODE_FIELDS, type)) { } else if (!has(NODE_FIELDS, type)) {
throw new Error(`Unknown node type: "${type}"`); throw new Error(`Unknown node type: "${type}"`);
} else { } else {

View File

@ -56,4 +56,20 @@ describe("cloneNode", function() {
expect(node.object).toBe(cloned.object); expect(node.object).toBe(cloned.object);
expect(node.property).toBe(cloned.property); expect(node.property).toBe(cloned.property);
}); });
it("should preserve type annotations", function() {
const node = t.variableDeclaration("let", [
t.variableDeclarator({
...t.identifier("value"),
typeAnnotation: t.anyTypeAnnotation(),
}),
]);
const cloned = t.cloneNode(node, /* deep */ true);
expect(cloned.declarations[0].id.typeAnnotation).toEqual(
node.declarations[0].id.typeAnnotation,
);
expect(cloned.declarations[0].id.typeAnnotation).not.toBe(
node.declarations[0].id.typeAnnotation,
);
});
}); });