Type checking in Angular 2 templates

angular template reference variable
angular binding types
angular 9 template type-checking
property binding angular
angular templates
angular string interpolation
angular template type cast
angular 6 data binding

We are building an application in Angular 2 and TypeScript. We try to statically check types where it is possible. Is there any way to check types in templates? Consider the following fragment:

<foo [data]="dataObj"></foo>

Assume that data in Foo component has some type TData. However, by default, nothing prevents me from passing dataObj that does not conform to TData. Is there a typescript extension for Angular templates that would verify the types in such a case?


Unfortunately, It seems that current Angular version doesn't check types of component inputs and events. You can use AOT compilation and enable fullTemplateTypeCheck angular compiler option, which performs some template type checking.

Enable fullTemplateTypeCheck option in src/tsconfig.app.json

{
    "compilerOptions": { ... },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true
        ...
    }
}

And build (or serve) your project with --aot option

ng build --aot

What about inputs and events type checking, I found two issues on angular bug tracker (issue1 and issue2). As I understand, the solution of the problem depends on renderer implementation, and more likely that the problem may be fixed in next version of angular renderer, called Ivy. Here is feature request for inputs type checking in ivy renderer.

Template syntax, Original answer: Unfortunately, It seems that current Angular version doesn't check types of component inputs and events. You can use AOT compilation and enable fullTemplateTypeCheck angular compiler option, which performs some template type checking. To be more precise, Angular creates Type Check Blocks (TCBs) based on the component template. Basically, a Type Check Block is a block of TypeScript code which can be inlined into source files, and when type checked by the TypeScript compiler will give us information about any typing errors in template expressions.


I think an IDE or linter might catch this for you, but if someone really needs this, one option would be to create a Pipe to do the type checking at run time.

@Pipe({ name: 'typeCheck' })
export class TypeCheckPipe implements PipeTransform {

  transform(value: any, classType: object): any[] {
    if (value &&
      !(value instanceof classType)
    ) {
        throw new TypeError("Input is not instanceof " + classType + 
                            " but was " + typeof(value));
    }
    return value;
  }
}

You can use it in a component template like this:

<custom-component [coolInput]="coolInput | typeCheck:coolInputClass"></custom-component>

The only catch I found is that I'm not sure how to inject the class function into the template other than as an instance of the component.

@Component({
  selector: 'my-app',
  template: `
  <div>
    <custom-component [coolInput]="coolInput | typeCheck:coolInputClass"></custom-component>
  </div>
  `,
})
export class App {
  coolInput: CoolInput;
  coolInputClass: object = CoolInput;

  constructor() {
    this.coolInput = "This is the wrong type";
  }
}

Here is a Plunker illustrating the working error message (thrown via Zone). https://plnkr.co/edit/WhoKSdoKUFvNbU3zWJy6?p=preview

Type checking in Angular 2 templates, To be more precise, Angular creates Type Check Blocks (TCBs) based on the component template. Basically, a Type Check Block is a block of TypeScript code which can be inlined into source files, and when type checked by the TypeScript compiler will give us information about any typing errors in template expressions. The simple way to use an Enum in a template is @Component() export class MyComp { public MyEnum: any = MyEnum; } Then in template: <select> <option value="MyEnum.ValueA">Value A</option> </select>


WebStorm from Jetbrains can do that.

My original answer:

I don't think there's a reliable way to do that without doing some think like React does with the JSX or TSX extension to the language.

The typescript compiler doesn't know about your HTML files, and will just ignore them. Also, there's no strong coupling between your templates and the Controller code... there's nothing preventing you from reusing the same template across several controllers.

Type-checking templates in Angular View Engine and Ivy, Learn tips to make Angular templates more aware of our data types and The content is likely be applicable for older Angular 2 or other Editors can provide autocompletion feedback and can detect typos in our templates. @m3l7 Yes, type checking is important, and is possible in Angular templates with typescript language service. On the other hand, having unlimited expressiveness in templates hinders tooling support and has other implications, such as how much energy one potentially needs to spend understanding a template file.


to quote the official statement:

In the template type-checking phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates.

Template validation produces error messages when a type error is detected in a template binding expression, similar to how type errors are reported by the TypeScript compiler against code in a .ts file.

More at:

Angular Template checking https://angular.io/guide/aot-compiler#binding-expression-validation

Yet to activate it, you should build the app, by

ng build --aot

or

ng build --prod

but you can also activate it without building:

ng serve --aot

Angular Tips: Template Binding with Static Types, We are building an application in Angular 2 and TypeScript. We try to statically check types where it is possible. Is there any way to check types in templates? Angular 2: Component Interaction, optional input parameters 0 How do you pass a parent components input value to two child components using the Router module in Angular 4?


If you are using visual studio code, you could try out the language service extension. Its still under heavy development, and you could consider it in beta. But when I would definitely say that it have made me more productive. Not only its type checking, but also cmd + clicking components to go to their source.

If I am not mistaken, this project will eventually be merged to vscode it self when its somewhat stable as its in vscode's best interest to keep angular developers productive.

You can rest assured about the extension's support because it's being worked on by the angular team. For more information checkout this readme

Edit: sublime text and webstorm support this too.

Type checking in Angular 2 templates - angular - html, On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love. In recent releases of Angular, type-checking has been extended to However, the type-checking within our template is not quite as clever  One of the Angular compiler's most helpful features is the ability to type-check expressions within templates, and catch any errors before they cause crashes at runtime. In the template type-checking phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates.


Using $any() To Temporarily Disable Type-Checking Within A , 2), if you use *ngFor instead of *ngIf . This is quite a clumsy hack - but works to achieve what the OP was trying to do: export type Product = { sku:  Like the name indicates, the ng-template directive represents an Angular template: this means that the content of this tag will contain part of a template, that can be then be composed together with other templates in order to form the final component template. Angular is already using ng-template under the hood in many of the structural directives that we use all the time: ngIf, ngFor and ngSwitch.


Type check directive template context · Issue #31556 · angular , When activated, the Angular compiler will be stricter when checking your templates and catch potential type errors (check our Angular 5.0 blog  The Angular application manages what the user sees and can do, achieving this through the interaction of a component class instance (the component) and its user-facing template. You may be familiar with the component/template duality from your experience with model-view-controller (MVC) or model-view-viewmodel (MVVM).


What's new in Angular 5.2?, Including core-js in the types array in EXCEPTION: Template parse errors: First of all check your angular-cli version with the following command  TypeScripts transpilation mechanism also performs type checking, however it only works when we tell TypeScript the type of things. e.g. in javascript we might write: let a; a = 1; a = '2'; We expected the type of the a variable to remain a number over its life.