LoginSignup
8
2

More than 1 year has passed since last update.

忘れそうなzodスキーマメモ

Last updated at Posted at 2022-03-30

概要

この記事は、著者が最近使った中で特に忘れそうなzodのスキーマについて簡単な説明とサンプル、使い方をまとめたメモです。

zod自体の説明、インストール方法や本記事で説明していないスキーマ等についてはライブラリのREADME.mdをご覧ください。

スキーマ

z.array

配列型を表すzodスキーマ

const stringArraySchema = z.array(z.string())
// 以下の記法と同様
// const stringArraySchema = z.string().array()

type StringArray = z.infer<typeof stringArraySchema>
// string[]

z.nullable

nullable型(null許容型)を表すzodスキーマ

const nullableStringSchema = z.string().nullable()
type NullableString = z.infer<typeof nullableStringSchema>
// string | null

前述のarrayに利用すると以下のようになる(nullではなく空配列にしたほうが扱いやすい)

const nullableStringArraySchema = z.array(z.string()).nullable()
type NullableStringArray = z.infer<typeof nullableStringArraySchema>
// string[] | null

z.optional

optional型(undefined許容型)を表すzodスキーマ

const optionalStringSchema = z.string().optional()
type OptionalString = z.infer<typeof optionalStringSchema>
// string | undefined

z.nullish

nullableかつoptionalな型を表すzodスキーマ

const nullishStringSchema = z.string().nullish()
// 以下の記法と同様
// const nullishStringSchema = z.string().nullable().optional()

type NullishStringArray = z.infer<typeof nullishStringSchema>
// string | null | undefined

z.literal

literal型(string型, number型, boolean型などの特定の値)を表すzodスキーマ

Date, bigint型は記事投稿時点でサポート対象外

const messageSchema = z.literal("message")
const oneSchema = z.literal(1)
const trueSchema = z.literal(true)

type Message = z.infer<typeof messageSchema>
// "message"
type One = z.infer<typeof oneSchema>
// 1
type True = z.infer<typeof trueSchema>
// true

z.union

union型を表すzodスキーマ

const stringOrNumberSchema = z.union([z.string(), z.number()])
// 引数が配列であることを忘れやすいので注意
// 以下の記法と同様
// const stringOrNumberSchema = z.string().or(z.number())

type StringOrNumber = z.infer<typeof stringOrNumberSchema>
// string | number

前述のliteral型と合わせて利用すると、以下のようになる

const someHttpStatusSchema = z.union([z.literal("200"), z.literal("404")])
type SomeHttpStatus = z.infer<typeof someHttpStatusSchema>
// "200" | "404"

z.nonempty

空文字列を許容しないstring型を表すスキーマ

const nonemptyStringSchema = z.string().nonempty()
type NonemptyString = z.infer<typeof nonemptyStringSchema>
// string(空文字は許容しない)

nonemptyとは逆に、空文字列のみを許容するstring型は以下のように書く

const emptyStringSchema = z.string().length(0)
type EmptyString = z.infer<typeof emptyString>
// string(空文字のみ許容する)
// z.string().empty()のような書き方は記事投稿時点では存在しない

z.any

any型(どの型でも許容する型)を表すzodスキーマ

型を定義している意味がなくなるので、使う場合は要注意

const anySchema = z.any()
type Any = z.infer<typeof anySchema>
// any

z.unknown

unknown型(どの型でも許容する型)を表すzodスキーマ

unknown型はany型とは異なり、型が確定するまでプロパティやメソッドを参照できない

const unknownSchema = z.unknown()
type Unknown = z.infer<typeof unknownSchema>
// unknown
8
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
2