Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ivy): input type coercion for template type-checking #33243

Closed
wants to merge 1 commit into from

Commits on Oct 23, 2019

  1. feat(ivy): input type coercion for template type-checking

    Often the types of an `@Input`'s field don't fully reflect the types of
    assignable values. This can happen when an input has a getter/setter pair
    where the getter always returns a narrow type, and the setter coerces a
    wider value down to the narrow type.
    
    For example, you could imagine an input of the form:
    
    ```typescript
    @input() get value(): string {
      return this._value;
    }
    
    set value(v: {toString(): string}) {
      this._value = v.toString();
    }
    ```
    
    Here, the getter always returns a `string`, but the setter accepts any value
    that can be `toString()`'d, and coerces it to a string.
    
    Unfortunately TypeScript does not actually support this syntax, and so
    Angular users are forced to type their setters as narrowly as the getters,
    even though at runtime the coercion works just fine.
    
    To support these kinds of patterns (e.g. as used by Material), this commit
    adds a compiler feature called "input coercion". When a binding is made to
    the 'value' input of a directive like MatInput, the compiler will look for a
    static field with the name ngAcceptInputType_value. If such a field is found
    the type-checking expression for the input will use the static field's type
    instead of the type for the @input field,allowing for the expression of a
    type conversion between the binding expression and the value being written
    to the input's field.
    
    To solve the case above, for example, MatInput might write:
    
    ```typescript
    class MatInput {
      // rest of the directive...
    
      static ngAcceptInputType_value: {toString(): string};
    }
    ```
    
    FW-1475 #resolve
    alxhub committed Oct 23, 2019
    Copy the full SHA
    46b5112 View commit details
    Browse the repository at this point in the history