Friday 5 May 2017

How to get TypeScript's static typings to work on runtime

function multiply(num: number): number {
  console.log(num * 10) // NaN
  return num * 10
}

multiply("not-a-number") // result == NaN

If i try to call the above function by hard-coding invalid argument type, Typescript will complain. Which is expected.

I was expecting same thing when argument is passed dynamically.

const valueFromDifferentSource = "not-a-number"
multiply(valueFromDifferentSource) // result == NaN

Instead of breaking the code. Javascript continues to execute the code and returns "Not-a-Number" NaN.

How do i achieve to get typescript's static type work on runtime?



via sravis

No comments:

Post a Comment