3

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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is there any library that does not have such issues and works easier with TS?
The new zod version resolved most of the issues and now works perfectly with typescript, so I suggest trying it!
Thanks for the update! I already started using Zod and is great 🙂

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.