Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [no-unnecessary-type-assertion] handle missing declarations #537

Merged
merged 4 commits into from Jun 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,
},
],
},
],
});