Skip to content

Template compiler should treat TypeScript ! on inputs as required inputs #24879

@jcomputer

Description

@jcomputer

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Performance issue
[X] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
[ ] Other... Please describe:

Current behavior

Currently, you cannot mark an @Input() as required a template compile time, you can just assert it is not undefined at runtime.

TypeScript supports (or requires, if you use strictPropertyInitialization) adding a ! to the end of instance property declarations which aren't initialized in-line or in the constructor to communicate to the type-checker that this variable is indeed defined, even if it doesn't appear to be.

The combination of the above two points means you end up with a sort of inconsistent state, in which you want to assert your inputs are defined in ngOnInit or ngOnChanges, yet the type-checker thinks they are already defined because you used the ! operator on their definitions.

Expected behavior

It would be nice if the template compiler could detect this operator on declarations of inputs, and take it to mean that input is required. This means the template compiler would give a (helpful) error if you used such a component but did not specify one of these required inputs, avoiding such mistakes at compile time instead of at runtime.

Minimal reproduction of the problem with instructions

http://plnkr.co/edit/7wr39D8FiEIb6JCteXr1?p=preview
(stackblitz doesn't support a new enough version of TypeScript, so I'm using plnkr)

What is the motivation / use case for changing the behavior?

In general, it would be useful to have a required parameter check as a compile-time check instead of a runtime check to both catch mistakes earlier and to reduce/simplify code (no manual checks and having to deal with checking in both ngOnInit and onChanges).

This is especially true now that TypeScript supports strictPropertyInitialization, which makes the aforementioned checks less idiomatic for TypeScript to do (since you assume the value is defined but check if it isn't defined).

Environment


TypeScript version 2.7+

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: coreIssues related to the framework runtime

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions