tam
tam

Reputation: 262

Why is runtime type checking so important in ts?

According to official documentation, typescript is a static type checker for javascript. These checks take place during compile time, i. e. before the program execution. Ts creators also state that they do not provide runtime type information or runtime type checking. For this reason, many libraries have been created for runtime data validation in ts: io-ts, joi, yup, zod, etc. and best practice seems to dictate that we use them.

Can someone maybe explain why is runtime type checking so important? What kind of errors can occur without it? Do you maybe have some practical examples?

Upvotes: 4

Views: 1454

Answers (1)

Konrad
Konrad

Reputation: 24661

Let say you have an api like https://yesno.wtf/api, it returns a json like that:

{
  "answer": "no",
  "forced": false,
  "image": "https://yesno.wtf/assets/no/20-56c4b19517aa69c8f7081939198341a4.gif"
}

But you can also type it like this:

type ResponseData = {
  answer: number[],
  forced: string,
  image: boolean[]
}

TypeScript will say it's fine, but it's isn't, it will throw errors in run time when you will try to do something like

image.map(() => /* */)

Because image is not really an array

Upvotes: 5

Related Questions