angularangular6

Is there a way to add a type assertion / annotation to a template input variable?


Background

I have a template that looks like this (I'm using some component that uses this as the basis for a repeated item, it's the <p-pickList>, but the question is not specific about that component, just as an example)

For background, let's say I have a type Foo and my component has a foos: Foo[], I'm feeding it to the <p-pickList> component under the [source] attribute and its doing the internal *ngFor for it, all I have to do is provide a template

 <ng-template let-foo pTemplate="item">
   ...
   {{ foo.anythingGoesHereWithNoWarningAndNoAutocomplete }}

However, the type information on foo seems to be lost.

I'm a big fan of type safety and I like that Intellij (or any other editor) can show me a warning if inside the template I do something like specifying an invalid attribute of foo

If I had a regular *ngFor, it would infer the type of foo

<div *ngFor="let foo of foos">
  {{ foo.autoCompleteWorksInMostIDEsAsWellAsWarningIfInvalidProp }}

Questions:

  1. Is there any syntax that will allow me to hint the type of let-foo? (and hopefully most IDE's will recognize).

  2. If I don't want to rely on IDE's, is there a way to have the ng compiler type check foo (declared by let-foo)?

tl;dr is there a syntax that let me type annotate the template input variable? e.g. something like this made up syntax?

let-foo="$implicit as Foo" or let-foo-type="Foo"?

Workaround

One silly idea is to have an identity function in my component, e.g.

identity(foo: Foo): Foo {
  return foo;
}

But doing

{{ identity(foo).fooProp }}

Is not a big improvement over

{{ (foo as Foo).fooProp }}`

Solution

  • VSCode should have that feature out of the box, just tested in stackblitz: https://stackblitz.com/edit/angular-type-assertion?file=src/app/app.component.html

    enter image description here