Skip to content

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

Closed
@bradzacher

Description

@bradzacher

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()!;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement: new plugin ruleNew rule request for eslint-pluginhas prthere is a PR raised to close thispackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions