Skip to content

Commit

Permalink
fix: avoid reporting 'Cannot find name '{0}'. Did you mean '{1}'?' fo…
Browse files Browse the repository at this point in the history
…r reactive variables (#126)

* Avoid reporting 'Cannot find name '{0}'. Did you mean '{1}'?' for reactive variables

* Destructure regex results, as requested in PR #126
  • Loading branch information
fatmirsukaliq authored Mar 29, 2020
1 parent 2b4412d commit a267885
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/transformers/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,25 @@ const TS_TRANSFORMERS = {
before: [importTransformer],
};

const TS2552_REGEX = /Cannot find name '\$([a-zA-Z0-9_]+)'. Did you mean '([a-zA-Z0-9_]+)'\?/i;
function isValidSvelteReactiveValueDiagnostic(
filename: string,
diagnostic: any,
): boolean {
if (diagnostic.code !== 2552) return true;

/** if the importee is not a svelte file, do nothing */
if (!isSvelteFile(filename)) return true;

/** if error message doesn't contain a reactive value, do nothing */
if (!diagnostic.messageText.includes('$')) return true;

const [, usedVar, proposedVar] =
diagnostic.messageText.match(TS2552_REGEX) || [];

return !(usedVar && proposedVar && usedVar === proposedVar);
}

function compileFileFromMemory(
compilerOptions: CompilerOptions,
{ filename, content }: { filename: string; content: string },
Expand Down Expand Up @@ -155,7 +174,11 @@ function compileFileFromMemory(
const diagnostics = [
...emitResult.diagnostics,
...ts.getPreEmitDiagnostics(program),
].filter(diagnostic => isValidSvelteImportDiagnostic(filename, diagnostic));
].filter(
diagnostic =>
isValidSvelteImportDiagnostic(filename, diagnostic) &&
isValidSvelteReactiveValueDiagnostic(filename, diagnostic),
);

return { code, map, diagnostics };
}
Expand Down
21 changes: 21 additions & 0 deletions test/transformers/typescript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,5 +141,26 @@ describe('transformer - typescript', () => {
);
expect(diagnostics.some(d => d.code === 2307)).toBe(true);
});

it('should NOT report a mismatched variable name error when using reactive variables', async () => {
const { diagnostics } = await transpile(
`
const user = {};
$user.name = "test";
`,
);
expect(diagnostics.some(d => d.code === 2552)).toBe(false);
});

it('should report a mismatched variable name error', async () => {
const { diagnostics } = await transpile(
`
const user = {};
xuser.name = "test";
`,
);
expect(diagnostics.some(d => d.code === 2552)).toBe(true);
});

});
});

0 comments on commit a267885

Please sign in to comment.