diff --git a/src/transformers/typescript.ts b/src/transformers/typescript.ts index 8078043c..61cb9a8a 100644 --- a/src/transformers/typescript.ts +++ b/src/transformers/typescript.ts @@ -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 }, @@ -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 }; } diff --git a/test/transformers/typescript.test.ts b/test/transformers/typescript.test.ts index 48f73726..a4a6364e 100644 --- a/test/transformers/typescript.test.ts +++ b/test/transformers/typescript.test.ts @@ -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); + }); + }); });