Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript argument type mismatch does not throw error

I'm trying to familiarize myself with typescript in angular 2+ and I'm encountering something that seems strange to me. An argument passed from my template to my component via a method does not match it's typing but is not throwing an error.

checkValue(value:number) {
  console.log(typeof value) // returns type 'string'
}

The source of the argument is coming from this button click event in my template:

<input type="number" #numberInput>
<button (click)="checkValue(numberInput.value)">+</button>

I believe the input tag is not enforcing a type on the value and is sending it as a string but I am curious why the compiler doesn't catch this.

like image 211
Joe Nixon Avatar asked Feb 03 '18 00:02

Joe Nixon


1 Answers

The key part here is:

in my template

The typescript compiler type checks your ts files and generates JS. Templates are processed by angular, and angular does not check types. Since at runtime ts becomes javascript, the function can be invoked from the template with any parameter type.

like image 162
Titian Cernicova-Dragomir Avatar answered Oct 22 '22 15:10

Titian Cernicova-Dragomir