Closed3

zodとyupのinferを比較してみる

dyoshikawadyoshikawa

infer は両方できる。

zod

import { z } from "zod"

const userSchema = z.object({
  name: z.string(),
  age: z.number(),
})
type User = z.infer<typeof userSchema>
// type User = {
//   name: string;
//   age: number;
// }

yup

import * as yup from "yup"

const userSchema = yup.object({
  name: yup.string().required(),
  age: yup.number().required(),
})
type User = yup.InferType<typeof userSchema>
// type User = {
//   name: string;
//   age: number;
// }
dyoshikawadyoshikawa

差となりそうなのはzodの .union() .enum() .literal() だろうか。

zod

import { z } from "zod"

const literalTypeSchema = z.literal("foo")
type LiteralType = z.infer<typeof literalTypeSchema>
// type LiteralType = "foo"

const unionType1Schema = z.union([z.string(), z.number()])
type UnionType1 = z.infer<typeof unionType1Schema>
// type UnionType1 = string | number

const unionType2Schema = z.union([z.literal("foo"), z.literal("bar")])
type UnionType2 = z.infer<typeof unionType2Schema>
// type UnionType2 = "foo" | "bar"

const unionType3Schema = z.union([z.literal(1), z.literal("foo")])
type UnionType3 = z.infer<typeof unionType3Schema>
// type UnionType3 = 1 | "foo"

const enumTypeSchema = z.enum(["foo", "bar"])
type EnumType = z.infer<typeof enumTypeSchema>
// type EnumType = "foo" | "bar"

zodはバリデーションとunion型の生成が可能。

yup

import * as yup from "yup"

const unionType = yup.string().oneOf(["foo", "bar"]).required()
type UnionType = yup.InferType<typeof unionType>
// type UnionType = string

yupでは、string or numberのようなバリデーションはカスタム機構を使わない限り難しい?

また、 .oneOf() でzodの .union().enum() 相当の検査は可能だが、 InferType の結果はプリミティブ型までしか得られなさそう。

このスクラップは2022/10/08にクローズされました