Escriu per cercar…

Schema

Schema validation with static type inference

Aquesta pàgina encara no s'ha traduït — es mostra en l'idioma original:English

Introduction

Zod is a TypeScript-first validation library.

In web applications, it is common to work with complex data that must be transmitted between different applications.

Using Zod, you can define schemas you can use to validate data, from a simple string to a complex nested object.

Json

When deserializing a JSON string, you can define its structure using a type to provide better autocompletion, error checking, and readability.

Modify the main.ts file:

ts
type Person = {
    name: string,
    age: number
}

let str = '{ "name": "Eva", "age": 33}'

let person: Person = JSON.parse(str)

console.log(person.name)

If you run this code, it works without problems because the deserialized object has the name property:

shell
deno main.ts
Eva

However, this is only informative, as JSON.parse does not verify that the string contains an object compatible with the variable type:

ts
type Person = {
    name: string,
    age: number
}

let str = '{"brand": "Seat", "model": "Ibiza"}'

let person: Person = JSON.parse(str)

console.log(person.name)

If you run the code, the result is undefined because the deserialized object does not have the name property:

Estàs llegint una vista prèvia.

Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.

Inicia sessió