Skip to content

Commit a267885

Browse files
fix: avoid reporting 'Cannot find name '{0}'. Did you mean '{1}'?' for reactive variables (#126)
* Avoid reporting 'Cannot find name '{0}'. Did you mean '{1}'?' for reactive variables * Destructure regex results, as requested in PR #126
1 parent 2b4412d commit a267885

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

Diff for: src/transformers/typescript.ts

+24-1
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,25 @@ const TS_TRANSFORMERS = {
8484
before: [importTransformer],
8585
};
8686

87+
const TS2552_REGEX = /Cannot find name '\$([a-zA-Z0-9_]+)'. Did you mean '([a-zA-Z0-9_]+)'\?/i;
88+
function isValidSvelteReactiveValueDiagnostic(
89+
filename: string,
90+
diagnostic: any,
91+
): boolean {
92+
if (diagnostic.code !== 2552) return true;
93+
94+
/** if the importee is not a svelte file, do nothing */
95+
if (!isSvelteFile(filename)) return true;
96+
97+
/** if error message doesn't contain a reactive value, do nothing */
98+
if (!diagnostic.messageText.includes('$')) return true;
99+
100+
const [, usedVar, proposedVar] =
101+
diagnostic.messageText.match(TS2552_REGEX) || [];
102+
103+
return !(usedVar && proposedVar && usedVar === proposedVar);
104+
}
105+
87106
function compileFileFromMemory(
88107
compilerOptions: CompilerOptions,
89108
{ filename, content }: { filename: string; content: string },
@@ -155,7 +174,11 @@ function compileFileFromMemory(
155174
const diagnostics = [
156175
...emitResult.diagnostics,
157176
...ts.getPreEmitDiagnostics(program),
158-
].filter(diagnostic => isValidSvelteImportDiagnostic(filename, diagnostic));
177+
].filter(
178+
diagnostic =>
179+
isValidSvelteImportDiagnostic(filename, diagnostic) &&
180+
isValidSvelteReactiveValueDiagnostic(filename, diagnostic),
181+
);
159182

160183
return { code, map, diagnostics };
161184
}

Diff for: test/transformers/typescript.test.ts

+21
Original file line numberDiff line numberDiff line change
@@ -141,5 +141,26 @@ describe('transformer - typescript', () => {
141141
);
142142
expect(diagnostics.some(d => d.code === 2307)).toBe(true);
143143
});
144+
145+
it('should NOT report a mismatched variable name error when using reactive variables', async () => {
146+
const { diagnostics } = await transpile(
147+
`
148+
const user = {};
149+
$user.name = "test";
150+
`,
151+
);
152+
expect(diagnostics.some(d => d.code === 2552)).toBe(false);
153+
});
154+
155+
it('should report a mismatched variable name error', async () => {
156+
const { diagnostics } = await transpile(
157+
`
158+
const user = {};
159+
xuser.name = "test";
160+
`,
161+
);
162+
expect(diagnostics.some(d => d.code === 2552)).toBe(true);
163+
});
164+
144165
});
145166
});

0 commit comments

Comments
 (0)