Skip to content

Warn on non-nullable optional chain #44870

@dgp1130

Description

@dgp1130

Which @angular/* package(s) are relevant/releated to the feature request?

compiler-cli

Description

Optional chaining is a great way to safely access properties that might be null or undefined, for example:

import {Component, Input} from '@angular/core';

@Component({
  template: `
    <span>Hello, {{ user?.name ?? 'guest' }}!</span>
  `,
})
export class Greeter {
  @Input() user?: User;
}

interface User {
  name: string;
}

But things can easily change and make the optional chain useless, such as:

  export class Greeter {
-   @Input() user?: User;
+   @Input() user: User;
  }

This change means that the optional chain user?.name is no longer useful because user will never be null or undefined. This leads to confusion and tricks readers of the code into thinking that there is a case where "Hello, guest!" is displayed, when that actually isn't the case. If the default "guest" string comes from somewhere else, it could lead to dead code and possibly result in excess bundle size.

Proposed solution

We should consider an extended diagnostic to identify and warn developers in this situation. We already have a diagnostic to warn about useless nullish coalescing operators ??, so it makes sense to have a similar check for optional chaining.

Alternatives considered

N/A

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions