Issue at Hand
After upgrading my Angular version from 10 to 13, I encountered a problem with the new TypeScript strict compiler mode. The upgrade required me to assign values to all declared variables upon initialization, causing issues with properties decorated as @Input()
in my components.
Now, I am faced with a dilemma: either disable the strict mode (which is not ideal) or add an exclamation point to every @Input()
property in every component.
@Input() something!: SomeType;
(used to ignore uninitialised properties)
The Question Arises
I am seeking guidance on Angular's official stance regarding this issue and any recommended best practices for handling it.
Perspectives on the Matter
The crux of the matter lies in the fact that @Input()
properties are meant to be initialized differently in Angular components compared to regular properties, as their values come from the parent component in the template. This calls for a different treatment within the Angular context.
I am hoping to find a solution where Angular takes charge of enforcing this specific strict check rather than leaving it solely to TypeScript.
My ideal scenario would involve bypassing the TypeScript strict check and indicating whether each input is compulsory or optional as part of the specific TypeScript build process for Angular. In this setup, Angular would analyze each instance of the component and determine based on the calling context in the parent HTML template whether to raise a compiler error.
For instance, if a component has inputs like these
@Input() compulsoryProp: string;
@Input() optionalProp: string = 'default value';
The new TypeScript compiler might flag compulsoryProp
and suggest turning it into
@Input() compulsoryProp: string | undefined = undefined;
However, I am reluctant to take this approach and instead prefer Angular to handle this logic and trigger a compilation error only when the compulsoryProp
is missing when calling the component in a parent template.
If this topic has been discussed elsewhere, I apologize. Surprisingly, there seems to be limited discussion on this subject online, with the main result being a related question on Stack Overflow, which did not provide a satisfactory answer.