Managing @Input Typing in Angular: A Perspective for Newcomers
Mikita Himpel
Posted on October 2, 2023
Hello everyone,
Being relatively new to Angular, I've found myself pondering over how to work with @Input
typisation, especially in applications where strict null checks are enabled. Let me present the variants I've observed and then offer an approach I've been considering.
The Variants:
-
Undefined Type:
@Input() field: Type | undefined;
This method does the job, but it also requires incorporating numerous 'if' conditions in the code, compromising its readability.
-
Asserting Input:
@Input() field!: Type;
A decent approach for Angular 15, where the input is mandatory. However, I've heard that Angular 16 won't present the same issues. There's also the risk that someone might initiate the input in the constructor, which might bypass any type or linting checks.
-
Default Value Initialization:
@Input() fields: Type[] = [];
This is feasible but isn't universally applicable.
From the official documentation, I've seen all three methods employed, leaving me sometimes perplexed as to why one was chosen over the others.
My Proposed Approach:
I'm thinking of a structure where:
- If the input is mandatory:
field!: Type
- If it's optional:
field?: Type
This method distinctly demarcates mandatory from optional inputs at the type level. Essentially, inputs should carry either a !
or ?
sign.
Now, there could be situations where the input is essential, but at the component's initialization phase, the value isn't available. For such scenarios, I suggest: field!: Type | null
. Analogously, for optional fields where data isn't ready during the component's initialization phase, we'd use: field?: Type | null
.
A Look Back at React:
Having previously coded in React, I didn't encounter such dilemmas in functional components. It was quite puzzling for me not to find a standardized solution for such a ubiquitous problem in Angular. It seems the issue stems from Angular's reliance on classes, which means inputs can't be initialized during the constructor phase. Interestingly, from my understanding, Vue 3 seems to have navigated away from this problem, albeit with a different strategy.
I'd love to get your feedback on this. If you've found alternative solutions or have insights into why one approach might be better than the others, please share. Let's make this journey into Angular smoother for everyone who's new!
Posted on October 2, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.