zod-class 中文文档教程

发布于 2年前 浏览 15 更新于 2年前

zod-class

这是一个小型实用程序库,与 Zod 一起使用,可以通过创建类在一行中定义类型和模式。

安装

npm install zod-class

使用

import z from "zod";
import { ZodClass } from "zod-class";

export class HelloSchema extends ZodClass({
  key: z.string(),
}) {}

const hello = new HelloSchema({
  key: "key",
});

为什么?

总是有类型和模式的冗余声明可能会很烦人:

  1. z.object
  2. 声明派生类型的
interface HelloSchema extends z.infer<typeof HelloSchema> {}
const HelloSchema = z.object({
  key: z.string(),
});

使用 z.infer zod-class 使得这可以在单行中实现。

它还提供了一个可以实例化的类并添加方法。

export class Person extends ZodClass({
  firstName: z.string(),
  lastName: z.string(),
}) {
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

警告

警告:静态 HelloSchema.parse 的返回类型不能准确反映它返回所创建类的实例,

const unknownValue: unknown;

// we wish it was `HelloSchema`, not `{ key: string }`.
const hello2: {
  key: string;
} = HelloSchema.parse(unknownValue);

解决方法:只需转换它

// option 1
const hello: HelloSchema = HelloSchema.parse(unknownValue);

// option 2
const hello = HelloSchema.parse<HelloSchema>(unknownValue);

zod-class

This is a small utility library to accompany Zod to enable for Types and Schemas to be defined in one line by creating a Class.

Installation

npm install zod-class

Usage

import z from "zod";
import { ZodClass } from "zod-class";

export class HelloSchema extends ZodClass({
  key: z.string(),
}) {}

const hello = new HelloSchema({
  key: "key",
});

Why?

It can be annoying to always have redundant declarations for types and schemas:

  1. the z.object declaration
  2. the derived type using z.infer
interface HelloSchema extends z.infer<typeof HelloSchema> {}
const HelloSchema = z.object({
  key: z.string(),
});

zod-class enables this to be achieved in a single line.

It also provides a class that can be instantiated and methods added to.

export class Person extends ZodClass({
  firstName: z.string(),
  lastName: z.string(),
}) {
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

Caveats

Caveat: the static HelloSchema.parse's return type does not accurately reflect that it returns an instance of the created class,

const unknownValue: unknown;

// we wish it was `HelloSchema`, not `{ key: string }`.
const hello2: {
  key: string;
} = HelloSchema.parse(unknownValue);

Workaround: just cast it

// option 1
const hello: HelloSchema = HelloSchema.parse(unknownValue);

// option 2
const hello = HelloSchema.parse<HelloSchema>(unknownValue);
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文