3

Angular can typecheck your templates in AOT and throw errors at compilation phase.

Unfortunately this doesn't seem to work when using as keyword, for example in ngIf:

*ngIf="typedVariable as newVariable" or in more common case, *ngIf="typedObservable | async as newVariable".

newVariable in both cases is not type safe, i.e. I can do {{ newVariable.anyInvalidPropertyNameNotPresentInTypedVariable }} without any errors or warnings (which is not the case with {{ typedVariable.anyInvalidPropertyNameNotPresentInTypedVariable }}).

Is there any way to achieve type safety, especially in async as case?

dunqan
  • 974
  • 7
  • 12
  • In your example, `newVariable` is just an alias of `typedVariable` and corresponds to the typed object emitted from the Observable. So the same behavior should be exposed whether you use `as` syntax or not. [**Because you are using `ngIf`**](https://angular.io/guide/aot-compiler#type-narrowing) Typescript compiler infers that `typedVariable` will never be undefined. – Michael Doye Jul 17 '18 at 10:12
  • Thank you @Und3rTow, can you confirm that in actual code? Because I've tried that, also with Ivy compiler, and it doesn't work as expected. – dunqan Jul 17 '18 at 11:18
  • Also, to clarity @Und3rTow, you are right, Typescript compiler infners that `typedVariable` will never be undefined, but because of `as` it will lose `typedVariable` type, i.e. `newVariable` will be treated "as `any`". – dunqan Jul 17 '18 at 12:02
  • I don't think it looses it's type. It's just that you can't implicitly "type check" it anymore because the `ngIf` directive acts as a guard so the erroneous property will not be displayed. – Michael Doye Jul 17 '18 at 12:09
  • Here is a fairly in-depth article on this - https://blog.angular-university.io/angular-reactive-templates/ – Michael Doye Jul 17 '18 at 12:14
  • Just to clarify one more thing, `typeVariable` is complex object and I don't want to validate if it is 'undefined' or not. `ngIf` works as a guard, that's great, I know it will not be undefined, but I also want to know, that if `typedVariable` is described by interface, for example `{ prop: string }` then I'll be warned about using it improperly, i.e. `{{ newVariable.porp }}` instead of `{{ newVariable.prop }}'. – dunqan Jul 17 '18 at 13:51
  • 1
    Yes I understand, and it is a perfectly reasonable expectation. To do it in that way, I guess you would need to drop the use of `ngIf` as well as the `async` pipe so that `fullTemplateTypeCheck` can validate the bindings at compile time. For what it's worth, there is an [open issue](https://github.com/angular/angular/issues/24598) for this specifically. – Michael Doye Jul 17 '18 at 14:21

0 Answers0