Zod: Why you’re using TypeScript wrong | by Adrien Gautier | ekino-france | Nov, 2023 – Beragampengetahuan
If you have some experience in web development, you have inevitably encountered runtime errors when working with external data coming from an API. Working with TypeScript helps to significantly reduce these errors by reminding the structure and type of any data, across the entire application. However, while TypeScript is good at preventing impossible operations on data known during compilation, it can be too permissive regarding external (in other words, unknown) data.
In this article, I will explain why TypeScript allows you to write code that can fail on runtime and how Zod can prevent these data-related errors.
As I said in the introduction, the idea behind TypeScript is to track the structure and type of any data across the entire code. This not only helps to provide autocompletion in the IDE, but it also prevents invalid operations that would cause errors during runtime. In theory, every possible runtime error can be predicted and identified during TypeScript compilation. But this is not the case.
Contents
Is TypeScript missing its goal?
In reality, TypeScript’s primary objective is to improve productivity. This means that TypeScript will always chose productivity over “safety”.
A good demonstration of this is the type any. It exists, yet it’s widely accepted that we shouldn’t use it. However, not writing a single any in our code doesn’t mean our application is immune from runtime errors. Take a look at the following snippet :
const obviouslyAnArticle: Article = JSON.parse(input); // input is a string
Because JSON.parse return type is any, it can be associated with a variable explicitly typed (as Articlein this example). Without writing any ourselves, we are telling TypeScript to ignore the runtime probability where the parsed content does not satisfy the type Article.
We have to keep in mind that
anyis often used in external definition files (and it doesn’t look like this is going to change) which means we must be even more careful.
unknown and assertions
If unknown was used instead of any the above snippet would not be possible. We would be required to write explicit assertions using the as keyword :
const shouldBeAnArticle = JSON.parse(input) as Article;
With this syntax, we explicitly tell TypeScript to lower its guard. It is still bad, but no longer hidden!
Type narrowing expressions
Instead of relying on unsafe type assertions, we can use type narrowing expressions.
“the process of refining types to more specific types than declared is called narrowing” — TypeScript documentation
For example, the typeof operator (provided by JavaScript) can determine an object’s type during runtime.
console.log(typeof 42);
// Expected log: "number"
When used in a condition, TypeScript is able to narrow the type of the object.
if(typeof input === "string") {
// input is narrowed to the type string
submit(input.toLowerCase());
}
This expression allows TypeScript to predict that input can only be a string in this scope.
While assertions tells TypeScript to trust the developer,
narrowing expressions infers types from the runtime logic.
Discrimination
While TypeScript can narrow types with many other expressions, this only makes sense when refining either unions or primitive types. I call that “types discrimination”.
type Fish = { swim: () => void };
type Bird = { fly: () => void };function move(animal: Fish | Bird) {
if ("swim" in animal) {
// input is narrowed to the type Fish
return animal.swim();
}
// input is narrowed to the type Bird
return animal.fly();
}
With the above example, the keyword in allows TypeScript to discriminate the type of the animal object.
With unkown data, types discrimination can be a waste of time:
if(typeof input !== "string") {
// input is still unkown
}
This means we cannot rely exclusively on type narrowing expressions for external data. We need another way to narrow the type down: data validation.
rencana pengembangan website
metode pengembangan website
jelaskan beberapa rencana untuk pengembangan website, proses pengembangan website, kekuatan dan kelemahan bisnis pengembangan website
, jasa pengembangan website, tahap pengembangan website, biaya pengembangan website
#Zod #youre #TypeScript #wrong #Adrien #Gautier #ekinofrance #Nov