Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-type-assertion] handle missing d…
Browse files Browse the repository at this point in the history
…eclarations (#537)
  • Loading branch information
bradzacher authored and JamesHenry committed Jun 9, 2019
1 parent b16409a commit c69f4b7
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 2 deletions.
Expand Up @@ -134,6 +134,11 @@ export default util.createRule<Options, MessageIds>({
*/
function isPossiblyUsedBeforeAssigned(node: ts.Expression): boolean {
const declaration = util.getDeclaration(checker, node);
if (!declaration) {
// don't know what the declaration is for some reason, so just assume the worst
return true;
}

if (
// non-strict mode doesn't care about used before assigned errors
isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks') &&
Expand Down
13 changes: 11 additions & 2 deletions packages/eslint-plugin/src/util/types.ts
Expand Up @@ -140,8 +140,17 @@ export function isNullableType(
export function getDeclaration(
checker: ts.TypeChecker,
node: ts.Expression,
): ts.Declaration {
return checker.getSymbolAtLocation(node)!.declarations![0];
): ts.Declaration | null {
const symbol = checker.getSymbolAtLocation(node);
if (!symbol) {
return null;
}
const declarations = symbol.declarations;
if (!declarations) {
return null;
}

return declarations[0];
}

/**
Expand Down
Expand Up @@ -95,6 +95,21 @@ declare const str: string | null;
foo(str!);
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/532
`
declare function a(a: string): any;
declare const b: string | null;
class Mx {
@a(b!)
private prop = 1;
}
`,
`
class Mx {
@a(b!)
private prop = 1;
}
`,
],

invalid: [
Expand Down Expand Up @@ -280,5 +295,30 @@ class Foo {
},
],
},
// https://github.com/typescript-eslint/typescript-eslint/issues/532
{
code: `
declare function a(a: string): any;
const b = 'asdf';
class Mx {
@a(b!)
private prop = 1;
}
`,
output: `
declare function a(a: string): any;
const b = 'asdf';
class Mx {
@a(b)
private prop = 1;
}
`,
errors: [
{
messageId: 'unnecessaryAssertion',
line: 5,
},
],
},
],
});

0 comments on commit c69f4b7

Please sign in to comment.