Setter and getter that have different types
TypeScript requires that both the getter and setter have the same type. For example code like this would create a type error.
public get size(): number {
return this._size;
}
public set size(value: number | string) {
this._size = coerceNumberProperty(value)
}
private _size = 10;
We sometimes want setter and getter on different scope especially when using a getter/setter pair for the input. In above example, string
should be allowed to be passed in and that value can be coerced into number . But Typescript enforces that setter has to take the same type as getter returns. So if the getter returns a number then the setter is stuck with the narrower type.
In order to deal with that, Angular came up with a workaround to allow mismatched type to be in getter and setter. It's to add a static property with the ngAcceptInputType_{prefix}
to the component class. In the example above, we'd add one line at the end of that block:
static ngAcceptInputType_size: string | number | null | undefined;
This way Typescript compiles and setter can allow to take a wider range of type than getter returns.
More reference please look at Angular doc on Template Type-checking.