Files

87 lines
2.1 KiB
Markdown

@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.
<code-example format="typescript" language="typescript">
import {Component} from '&commat;angular/core';
&commat;Component({
template: `<div>{{ foo?.bar }}</div>`,
// &hellip;
})
class MyComponent {
// `foo` is declared as an object which *cannot* be `null` or `undefined`.
foo: { bar: string} = { bar: 'bar'};
}
</code-example>
## 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.
<code-example format="typescript" language="typescript">
import {Component} from '&commat;angular/core';
&commat;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>`,
// &hellip;
})
class MyComponent {
foo: { bar: string} | null = { bar: 'bar'};
}
</code-example>
If the input should not be nullable, delete the `?` operator.
<code-example format="typescript" language="typescript">
import {Component} from '&commat;angular/core';
&commat;Component({
// Template always displays `bar` as `foo` is guaranteed to never be `null` or `undefined`
template: `<div>{{ foo.bar }}</div>`,
// &hellip;
})
class MyComponent {
foo: { bar: string} = { bar: 'bar'};
}
</code-example>
## What if I can't avoid this?
This diagnostic can be disabled by editing the project's `tsconfig.json` file:
<code-example format="json" language="json">
{
"angularCompilerOptions": {
"extendedDiagnostics": {
"checks": {
"optionalChainNotNullable": "suppress"
}
}
}
}
</code-example>
See [extended diagnostic configuration](extended-diagnostics#configuration) for more info.
<!-- links -->
<!-- external links -->
<!-- end links -->
@reviewed 2023-03-02