Issue
So I've written a component that is getting an array or null as an input (to be async pipe compatible) though my getter and backing field can never return null, as this is handled by the ?? operator in the setter.
@Input()
public set items(values: T[] | null) {
this._items = values ?? [];
}
public get items() {
return this._items;
}
private _items: T[] = [];
Stackblitz: https://stackblitz.com/edit/generic-items-list-if-should-cannot-be-null?file=src%2Fmain.ts
I tried chaining with the ? operator which results in object can be undefined and i tried to get rid of the T type. Both times the issue is persisting.
Solution
The problem lies in the template.
Try this out:
@if(items?.length){
<p>items are availlable</p>
}
It is because the accesors
(set
and get
have the same argument/retun type), therefore having this:
public set items(values: T[] | null) {
this._items = values ?? [];
}
public get items() {
return this._items;
}
the get
will return T[] | null
type.
Wrapping up:
if you change the argument type of the set
from T[] | null
to T[]
everything will work safely at runtime since every nullish
value is escaped by this this._items = values ?? []
. Your final code could be like this:
Component:
export class GenericTableComponent<T = unknown> {
@Input()
public set items(values: T[]) {
this._items = values ?? [];
}
public get items() {
return this._items;
}
private _items: T[] = [];
}
And its template:
@if(items.length){
<p>items are availlable</p>
}
Answered By - NgDaddy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.