Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 709
msTam Avatar asked Sep 03 '25 17:09

msTam


1 Answers

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

like image 102
Konrad Linkowski Avatar answered Sep 05 '25 05:09

Konrad Linkowski