Canonical: Marking @Input as required
See original GitHub issueš feature request
Relevant Package
This feature request is for @angular/core
Description
There is a long history of discussion about whether / how to have the compiler enforce that specific inputs are provided to components: #11904 #18156 #24879 #28403 #30974
However, all of those are now closed and locked. They contain some advice about how to mitigate the problem, or kick the can down the road (āOne day I hope weāll be able to do this. That day is not today.ā), but thanks to the lock-bot none of them can be used to continue the conversation, so I guess we need yet another issue, because I believe the problem still exists.
Describe the solution youād like
It should be possible to annotate inputs such that using a component in a template without providing a value for that input is a compile-time error. Template checking has come a long way, and itās already possible for the compiler to flag providing the wrong type as an argument. Combine with the strictPropertyInitializers
flag, and such a check could rely on the existing !
assertion operator.
Describe alternatives youāve considered
The best approach Iāve seen while reviewing the above issues is specifying the required attributes in the selector
component metadata, but a) apparently that wonāt catch passing null
or undefined
to an Input that not defined with a type that includes those values, and b) that appears to break certain test harnesses? Also, I havenāt started using strictTemplates
/ fullTemplateTypeCheck
yet due to some problems in previous versions with narrowing on *ngIf
that may or may not have been resolved ā those existing capabilities may address some or all of this need.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:54
- Comments:25 (1 by maintainers)
Top GitHub Comments
For information, it is what Ionicās Stencil is doing.
Even if you fix the docs, and start promoting this approach, I still think itās not ok. First, the error will be wrong, as the compiler will complain about not finding the component, instead of the desired error. Secondly, if you leave the selector, without the attribute, and use the component. You will end up in with a strange behavior. If you pass an
undefined
value, the compiler will complain, but if you skip the attribute, it will work, even though the runtime behavior is the same.Thatās why I think, the best approach is to treat them the same, meaning that an error should occur, similar to passing an
undefined
value, as thatās how the runtime behavior is.Edit: The above example is reproducible in strict mode, Iām not sure if it works outside it.