-
Notifications
You must be signed in to change notification settings - Fork 27k
Description
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