I am looking to enhance my application by implementing Angular's template Strict mode through the configuration of
"strictTemplates": true
within tsconfig.json
. However, encountering an unexpected error after running ng serve
with this updated configuration.
One issue I have is with a shared component that is extensively used throughout the application.
@Component({
selector: 'my-shared-component',
...
})
export class SharedComponent {
@Input() selectedId: string | number;
@Output() selectedIdChange = new EventEmitter<string | number>()
@Input() disabled: boolean;
...
}
Specifying
<my-shared-component disabled="true">
triggers an error, which is understandable.
The real challenge arises when attempting to pass a number
into the
@Input() selectedId: string | number;
, such as:
export class OtherComponent {
myNumberId: number;
...
}
<my-shared-component [(selectedId)]="myNumberId">
An error is then thrown:
TS2322: Type 'string | number' is not assignable to type 'number'
Refactoring the data type of myNumberId
to string | number
is not a feasible solution since it is also utilized in another component where @Input id: number
is required (and must remain a number). Moreover, myNumberId
originates from the server and its type is known to be a number, making the replacement with string | number
seem inadequate.
Disabling the strictAttributeTypes configuration is not desirable either, as it would eliminate errors triggered by
<my-shared-component disabled="true">
.
I am exploring the possibility of using a typescript utility type (or similar tool) to restrict
@Input() selectedId: string | number
to only accept strings or numbers, without mandating the variables from the parent components to be string | number
. Alternatively, I am open to other suggestions for resolving this issue.