Skip to content
This repository has been archived by the owner on Oct 5, 2021. It is now read-only.

Commit

Permalink
fix(core): Invalid code produced for parameter destructuring with def…
Browse files Browse the repository at this point in the history
…ault values

fix #83
  • Loading branch information
urish committed Nov 28, 2018
1 parent 6ec5225 commit aa83a02
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
16 changes: 16 additions & 0 deletions packages/typewiz-core/src/integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,22 @@ describe('regression tests', () => {
});
`);
});

it('issue #83: invalid code produced for parameter destructuring with default values', () => {
const input = `
function greet({ who = "" }) {
return 'Hello, ' + who;
}
greet({who: 'world'});
`;

expect(typeWiz(input)).toBe(`
function greet({ who = "" }: { who: string }) {
return 'Hello, ' + who;
}
greet({who: 'world'});
`);
});
});

describe('apply-types options', () => {
Expand Down
27 changes: 26 additions & 1 deletion packages/typewiz-core/src/transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,30 @@ function createTwizInstrumentStatement(name: string, fileOffset: number, filenam
);
}

function removeInitializerFromBindingElement(node: ts.BindingElement) {
return ts.updateBindingElement(node, node.dotDotDotToken, node.propertyName, node.name, undefined);
}

function removeInitializerFromBindingName(node: ts.BindingName) {
if (ts.isObjectBindingPattern(node)) {
return ts.updateObjectBindingPattern(node, node.elements.map(removeInitializerFromBindingElement));
} else if (ts.isArrayBindingPattern(node)) {
return ts.updateArrayBindingPattern(node, node.elements.map(removeInitializerFromBindingElement));
} else {
return node;
}
}

function getParameterName(param: ts.ParameterDeclaration) {
const { name } = param;
if (ts.isObjectBindingPattern(name) || ts.isArrayBindingPattern(name)) {
const cleanName = removeInitializerFromBindingName(name);
return ts.createPrinter().printNode(ts.EmitHint.Unspecified, cleanName, param.getSourceFile());
} else {
return param.name.getText();
}
}

function visitorFactory(
ctx: ts.TransformationContext,
source: ts.SourceFile,
Expand Down Expand Up @@ -165,8 +189,9 @@ function visitorFactory(
if (!hasParensAroundArguments(node)) {
opts.parens = [node.parameters[0].getStart(), node.parameters[0].getEnd()];
}
const parameterName = getParameterName(param);
instrumentStatements.push(
createTwizInstrumentStatement(param.name.getText(), typeInsertionPos, source.fileName, opts),
createTwizInstrumentStatement(parameterName, typeInsertionPos, source.fileName, opts),
);
}
}
Expand Down

0 comments on commit aa83a02

Please sign in to comment.