8000 fix(eslint-plugin): [no-unnecessary-type-assertion] handle missing d… · Feiyang1/typescript-eslint@c69f4b7 · GitHub
Skip to content

Commit c69f4b7

Browse files
bradzacherJamesHenry
authored andcommitted
fix(eslint-plugin): [no-unnecessary-type-assertion] handle missing declarations (typescript-eslint#537)
1 parent b16409a commit c69f4b7

File tree

3 files changed

+56
-2
lines changed

3 files changed

+56
-2
lines changed

packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,11 @@ export default util.createRule<Options, MessageIds>({
134134
*/
135135
function isPossiblyUsedBeforeAssigned(node: ts.Expression): boolean {
136136
const declaration = util.getDeclaration(checker, node);
137+
if (!declaration) {
138+
// don't know what the declaration is for some reason, so just assume the worst
139+
return true;
140+
}
141+
137142
if (
138143
// non-strict mode doesn't care about used before assigned errors
139144
isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks') &&

packages/eslint-plugin/src/util/types.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,17 @@ export function isNullableType(
140140
export function getDeclaration(
141141
checker: ts.TypeChecker,
142142
node: ts.Expression,
143-
): ts.Declaration {
144-
return checker.getSymbolAtLocation(node)!.declarations![0];
143+
): ts.Declaration | null {
144+
const symbol = checker.getSymbolAtLocation(node);
145+
if (!symbol) {
146+
return null;
147+
}
148+
const declarations = symbol.declarations;
149+
if (!declarations) {
150+
return null;
151+
}
152+
153+
return declarations[0];
145154
}
146155

147156
/**

packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,21 @@ declare const str: string | null;
9595
9696
foo(str!);
9797
`,
98+
// https://github.com/typescript-eslint/typescript-eslint/issues/532
99+
`
100+
declare function a(a: string): any;
101+
declare const b: string | null;
102+
class Mx {
103+
@a(b!)
104+
private prop = 1;
105+
}
106+
`,
107+
`
108+
class Mx {
109+
@a(b!)
110+
private prop = 1;
111+
}
112+
`,
98113
],
99114

100115
invalid: [
@@ -280,5 +295,30 @@ class Foo {
280295
},
281296
],
282297
},
298+
// https://github.com/typescript-eslint/typescript-eslint/issues/532
299+
{
300+
code: `
301+
declare function a(a: string): any;
302+
const b = 'asdf';
303+
class Mx {
304+
@a(b!)
305+
private prop = 1;
306+
}
307+
`,
308+
output: `
309+
declare function a(a: string): any;
310+
const b = 'asdf';
311+
class Mx {
312+
@a(b)
313+
private prop = 1;
314+
}
315+
`,
316+
errors: [
317+
{
318+
messageId: 'unnecessaryAssertion',
319+
line: 5,
320+
},
321+
],
322+
},
283323
],
284324
});

0 commit comments

Comments
 (0)
0