ホーム 全セッション S03

値の制約への同じ形の適用

発展 1 / 4 目安 時間外

ページ一覧

あとで読む: 支払金額のように、ID以外の値の制約も同じ形で型に残せます。

Branded Type の用途は、IDの区別に限りません。支払金額を number のまま渡すと、受け取る関数からは、その値が検査済みか判別できません。

brand(ブランド)を付けると、「1以上の整数」という制約を型に残せます。ここではブランドの名前に、文字列の代わりに PaymentAmountBrand(Symbol)を使っています。.brand<"AppointmentId">() と役割は同じです。PaymentAmount.parse(1000) は Ok を返し、0、-100、1.5 は Err を返します。

範囲を変更するときは、schema の1か所を修正します。as を使うと検査を回避できるため、consistent-type-assertions のルールで as の使用を検出します。

支払金額の型の例 examples/final/src/domain/appointment/paymentAmount.ts
import { z } from "zod";

import { schemaResult } from "../shared/schemaResult.js";

const PaymentAmountBrand = Symbol();
const PaymentAmountSchema = z.number().int().positive().brand<typeof PaymentAmountBrand>();

export type PaymentAmount = z.infer<typeof PaymentAmountSchema>;

export const PaymentAmount = {
  schema: PaymentAmountSchema,
  parse: schemaResult(PaymentAmountSchema),
} as const;