Angular component input static typing

2.5k Views Asked by At

I have 2 angular components.

ButtonComponent that has an input of type ButtonText

@Component({
  selector: 'app-button',
  template: '<h1></h1>',
})
export class ButtonComponent {
  @Input() text: ButtonText;
}

export class ButtonText {
  constructor(private text: string) {
  }
}

And MainComponent that uses button and passes input to it:

@Component({
  selector: 'app-root',
  template: '<app-button [text]="title"></app-button>',
})
export class AppComponent {
  title = 'compiler-playground';
  test: ButtonText = new ButtonText('text');
}

Problem - if I pass a parameter with wrong type to input. ng build returns no any errors or warnings. I have tried a lot of possible angular compiler flags described [in angular docs]:(https://github.com/angular/angular/blob/master/aio/content/guide/aot-compiler.md#compiler-options)

"angularCompilerOptions": {
    "strictMetadataEmit": true,
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true,
    "skipTemplateCodegen": false,
    "trace": true,
    "debug": true
}

Question: how can I achieve static type checking during compilation? Or maybe there are any static analysis tools that can achieve this such as template linters?

1

There are 1 best solutions below

4
Suresh Kumar Ariya On

With help of EsLint/TSLint, we can apply static type checking to the component properties and input types.

export type inputType = 'Angular' | 'React Native' | 'Vue JS';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit {
  @Input() name: inputType;

  ngOnInit(){
    this.name = 'Angular'; //this works
    this.name = 'Angular123'; //this will throw errors
  }

}

If we pass 'Angular123' as value to @input 'name' from parent component, it won't throw error. Because we are passing dynamic values using attribute binding and these things will happen in run time and AOT compiler can't able to catch and report us back.

It's only possible in development time, With help of IDE Language services, TSLint will throw error, if we are trying to assign some values that doesn't belong to Types.