Skip to content

Rule suggestion: flag non-null assertion applied to an optional chain #1398

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

Closed
bradzacher opened this issue Jan 1, 2020 · 0 comments · Fixed by #1469
Closed

Rule suggestion: flag non-null assertion applied to an optional chain #1398

bradzacher opened this issue Jan 1, 2020 · 0 comments · Fixed by #1469
Labels
enhancement: new plugin rule New rule request for eslint-plugin has pr there is a PR raised to close this package: eslint-plugin Issues related to @typescript-eslint/eslint-plugin

Comments

@bradzacher
Copy link
Member

The optional chain operator is built such that it will return undefined if there is a nullish member.

Ending an optional chain expression with a non-null assertion is blatantly incorrect, and leads to type safety holes in your code, which will likely lead to runtime errors.

It is much better to either hoist the non-null assertion up the chain, so the thing you "know" is nullish is asserted on, instead of the entire expression.

function foo(x?: { a?: () => {} }) {
    return x?.a!;
}
function bar(x?: { a?: () => {} }) {
    return x?.a()!;
}
@bradzacher bradzacher added package: eslint-plugin Issues related to @typescript-eslint/eslint-plugin enhancement: new plugin rule New rule request for eslint-plugin labels Jan 1, 2020
@bradzacher bradzacher added the has pr there is a PR raised to close this label Jan 18, 2020
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 20, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement: new plugin rule New rule request for eslint-plugin has pr there is a PR raised to close this package: eslint-plugin Issues related to @typescript-eslint/eslint-plugin
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant