Rikard Axelsson
Rikard Axelsson

Reputation: 35

Runtime data validation for TypeScript

TypeScript has no runtime check to ensure that loaded data matches the types. We currently use JSON schemas that we generate from our types with typescript-json-schema via a CLI and then validate in runtime with ajv. A great solution we thought until we found that it didn't play well with JS dates since dates are not part of JSON.

Does anyone have a solution for this? We use types not classes.

Upvotes: 3

Views: 2878

Answers (1)

KiraLT
KiraLT

Reputation: 2607

You can use zod library. You will only need to have one schema and you can use it to generate types & validate data using JSON Schema.

Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type/structure, from a simple string to a complex nested object.

Take a look at this example:

import * as z from 'zod'

const schema = z.object({
    stringValue: z.string(),
    numberValue: z.number(),
    dateValue: z.date()
})

type MyType = z.infer<typeof schema>
// type MyType = {
//     stringValue: string;
//     numberValue: number;
//     dateValue: Date;
// }

const data = schema.parse({
    stringValue: 'Hello',
    numberValue: 1,
    dateValue: new Date()
})

The biggest issue with this library is that it doesn't work well when you need to transform data (e.g. you get the date as a string). It has an open issue regarding data transformation. Also, you can't generate JSON schema from zod instance (check the issue).

Zod 3 resolved data transformation

Upvotes: 4

Related Questions