sravis
sravis

Reputation: 3680

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?

Upvotes: 0

Views: 137

Answers (2)

Sergey Yarotskiy
Sergey Yarotskiy

Reputation: 4804

Typescript has nothing to do with runtime. But there is a good library for controlling variable types https://github.com/hapijs/joi. What you usually want to do, is to validate all the input data to your application (http requests, responses from other services, queue messages). Having such validation and static typing internally on a stage of writing a code, should give you what you want and improve code quality as well.

Upvotes: 0

Jeff Huijsmans
Jeff Huijsmans

Reputation: 1418

Make sure the valueFromDifferentSource has a typing as well:

const valueFromDifferentSource: number = "not-a-number"

TypeScript does nothing in run-time. It compiles TypeScript to plain Javascript, and adds nothing in the sense of boiler-plate code which allows run-time checks.

Upvotes: 3

Related Questions