2.1 KiB
@name Optional chain not nullable
@description
This diagnostic detects when the left side of an optional chain operation (.?) does not include null or undefined in its type in Angular templates.
import {Component} from '@angular/core';
@Component({
template: <div>{{ foo?.bar }}</div>,
// …
})
class MyComponent {
// foo is declared as an object which cannot be null or undefined.
foo: { bar: string} = { bar: 'bar'};
}
What should I do instead?
Update the template and declared type to be in sync. Double-check the type of the input and confirm whether it is actually expected to be nullable.
If the input should be nullable, add null or undefined to its type to indicate this.
import {Component} from '@angular/core';
@Component({
// If foo is nullish, bar won't be evaluated and the express will return the nullish value (null or undefined).
template: <div>{{ foo?.bar }}</div>,
// …
})
class MyComponent {
foo: { bar: string} | null = { bar: 'bar'};
}
If the input should not be nullable, delete the ? operator.
import {Component} from '@angular/core';
@Component({
// Template always displays bar as foo is guaranteed to never be null or undefined
template: <div>{{ foo.bar }}</div>,
// …
})
class MyComponent {
foo: { bar: string} = { bar: 'bar'};
}
What if I can't avoid this?
This diagnostic can be disabled by editing the project's tsconfig.json file:
{ "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "optionalChainNotNullable": "suppress" } } } }
See extended diagnostic configuration for more info.
@reviewed 2023-03-02