Type checking in Angular 2 templates

后端 未结 7 508
夕颜
夕颜 2021-02-02 06:07

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 fol

7条回答
  •  醉梦人生
    2021-02-02 06:18

    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:

    
    

    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: `
      
    `, }) 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

提交回复
热议问题