TypeScript โปรเจกต์: form validation library



สร้าง validation library จิ๋ว (แนว zod) — เข้าใจว่า z.infer และ schema-to-type ทำงานยังไง

เป้าหมาย

const userSchema = object({
  name: string().min(1),
  age: number().min(0).max(150),
  email: string().email(),
  role: literal("admin", "editor", "viewer"),
  bio: optional(string()),
});

type User = Infer<typeof userSchema>;
// { name: string; age: number; email: string; role: "admin" | "editor" | "viewer"; bio?: string }

const result = userSchema.parse(input);   // Result<User, ValidationError[]>

src/types.ts

export type ValidationIssue = {
  path: string[];
  message: string;
};

export type ParseResult<T> =
  | { success: true; data: T }
  | { success: false; issues: ValidationIssue[] };

// interface พื้นฐานของทุก validator
export interface Validator<T> {
  readonly _type: T;   // phantom type — ใช้ infer, ไม่มีค่าจริง
  parse(value: unknown, path?: string[]): ParseResult<T>;
}

// Infer — ดึง type ออกจาก validator
export type Infer<V> = V extends Validator<infer T> ? T : never;

src/primitives.ts

import type { Validator, ParseResult, ValidationIssue } from "./types.js";

function issue(path: string[], message: string): ValidationIssue {
  return { path, message };
}

// --- string ---
interface StringValidator extends Validator<string> {
  min(n: number): StringValidator;
  max(n: number): StringValidator;
  email(): StringValidator;
}

export function string(): StringValidator {
  const checks: Array<(v: string, path: string[]) => ValidationIssue | null> = [];

  const validator: StringValidator = {
    _type: "" as string,

    parse(value, path = []): ParseResult<string> {
      if (typeof value !== "string") {
        return { success: false, issues: [issue(path, `ต้องเป็น string ได้ ${typeof value}`)] };
      }
      const issues = checks.map((c) => c(value, path)).filter((x): x is ValidationIssue => x !== null);
      return issues.length > 0
        ? { success: false, issues }
        : { success: true, data: value };
    },

    min(n) {
      checks.push((v, p) => (v.length < n ? issue(p, `ต้องยาวอย่างน้อย ${n}`) : null));
      return validator;
    },
    max(n) {
      checks.push((v, p) => (v.length > n ? issue(p, `ยาวเกิน ${n}`) : null));
      return validator;
    },
    email() {
      checks.push((v, p) => (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? null : issue(p, "อีเมลไม่ถูกต้อง")));
      return validator;
    },
  };
  return validator;
}

// --- number ---
interface NumberValidator extends Validator<number> {
  min(n: number): NumberValidator;
  max(n: number): NumberValidator;
  int(): NumberValidator;
}

export function number(): NumberValidator {
  const checks: Array<(v: number, path: string[]) => ValidationIssue | null> = [];

  const validator: NumberValidator = {
    _type: 0 as number,
    parse(value, path = []): ParseResult<number> {
      if (typeof value !== "number" || Number.isNaN(value)) {
        return { success: false, issues: [issue(path, "ต้องเป็นตัวเลข")] };
      }
      const issues = checks.map((c) => c(value, path)).filter((x): x is ValidationIssue => x !== null);
      return issues.length > 0 ? { success: false, issues } : { success: true, data: value };
    },
    min(n) { checks.push((v, p) => (v < n ? issue(p, `ต้อง >= ${n}`) : null)); return validator; },
    max(n) { checks.push((v, p) => (v > n ? issue(p, `ต้อง <= ${n}`) : null)); return validator; },
    int() { checks.push((v, p) => (Number.isInteger(v) ? null : issue(p, "ต้องเป็นจำนวนเต็ม"))); return validator; },
  };
  return validator;
}

// --- literal union ---
export function literal<const T extends readonly (string | number | boolean)[]>(
  ...values: T
): Validator<T[number]> {
  return {
    _type: values[0] as T[number],
    parse(value, path = []): ParseResult<T[number]> {
      return values.includes(value as T[number])
        ? { success: true, data: value as T[number] }
        : { success: false, issues: [issue(path, `ต้องเป็นหนึ่งใน ${values.join(", ")}`)] };
    },
  };
}

// --- optional ---
export function optional<T>(inner: Validator<T>): Validator<T | undefined> {
  return {
    _type: undefined as T | undefined,
    parse(value, path = []): ParseResult<T | undefined> {
      if (value === undefined) return { success: true, data: undefined };
      return inner.parse(value, path);
    },
  };
}

src/object.ts — หัวใจของการ infer

import type { Validator, ParseResult, ValidationIssue, Infer } from "./types.js";

// shape → type: แยก optional key ออก
type ObjectShape = Record<string, Validator<unknown>>;

type InferObject<S extends ObjectShape> = {
  // key ที่ inner type รวม undefined → optional
  [K in keyof S as undefined extends Infer<S[K]> ? K : never]?: Infer<S[K]>;
} & {
  [K in keyof S as undefined extends Infer<S[K]> ? never : K]: Infer<S[K]>;
};

// prettify — ทำให้ hover แสดง type สวย
type Prettify<T> = { [K in keyof T]: T[K] } & {};

interface ObjectValidator<S extends ObjectShape>
  extends Validator<Prettify<InferObject<S>>> {}

export function object<S extends ObjectShape>(shape: S): ObjectValidator<S> {
  type T = Prettify<InferObject<S>>;
  return {
    _type: {} as T,
    parse(value, path = []): ParseResult<T> {
      if (typeof value !== "object" || value === null) {
        return { success: false, issues: [{ path, message: "ต้องเป็น object" }] };
      }

      const record = value as Record<string, unknown>;
      const result: Record<string, unknown> = {};
      const allIssues: ValidationIssue[] = [];

      for (const key in shape) {
        const fieldValidator = shape[key]!;
        const fieldResult = fieldValidator.parse(record[key], [...path, key]);
        if (fieldResult.success) {
          if (fieldResult.data !== undefined) {
            result[key] = fieldResult.data;
          }
        } else {
          allIssues.push(...fieldResult.issues);
        }
      }

      return allIssues.length > 0
        ? { success: false, issues: allIssues }
        : { success: true, data: result as T };
    },
  };
}

src/index.ts

export { string, number, literal, optional } from "./primitives.js";
export { object } from "./object.js";
export type { Infer, ParseResult, ValidationIssue } from "./types.js";

ใช้งาน

import { object, string, number, literal, optional, type Infer } from "./index.js";

const registerSchema = object({
  username: string().min(3).max(20),
  password: string().min(8),
  age: number().int().min(13),
  role: literal("user", "admin"),
  referralCode: optional(string()),
});

type RegisterInput = Infer<typeof registerSchema>;
// {
//   username: string;
//   password: string;
//   age: number;
//   role: "user" | "admin";
//   referralCode?: string;
// }

function handleRegister(body: unknown) {
  const result = registerSchema.parse(body);

  if (!result.success) {
    return { status: 422, errors: result.issues };
  }

  const input: RegisterInput = result.data;   // fully typed
  createUser(input);
  return { status: 201 };
}

handleRegister({ username: "ab", password: "123", age: 10, role: "superadmin" });
// { status: 422, errors: [
//   { path: ["username"], message: "ต้องยาวอย่างน้อย 3" },
//   { path: ["password"], message: "ต้องยาวอย่างน้อย 8" },
//   { path: ["age"], message: "ต้อง >= 13" },
//   { path: ["role"], message: "ต้องเป็นหนึ่งใน user, admin" },
// ]}

test

import { describe, it, expect, expectTypeOf } from "vitest";
import { object, string, number, optional, type Infer } from "./index.js";

const schema = object({
  name: string().min(1),
  age: number().min(0),
  nick: optional(string()),
});

describe("form validator", () => {
  it("type inference ถูก", () => {
    type T = Infer<typeof schema>;
    expectTypeOf<T>().toEqualTypeOf<{ name: string; age: number; nick?: string }>();
  });

  it("parse ผ่าน", () => {
    const r = schema.parse({ name: "อร", age: 25 });
    expect(r.success).toBe(true);
    if (r.success) expect(r.data).toEqual({ name: "อร", age: 25 });
  });

  it("รวม issue จากทุก field", () => {
    const r = schema.parse({ name: "", age: -1 });
    expect(r.success).toBe(false);
    if (!r.success) {
      expect(r.issues).toHaveLength(2);
      expect(r.issues.map((i) => i.path[0])).toEqual(["name", "age"]);
    }
  });
});

จุดที่ใช้ความรู้จากบทก่อน

ส่วนบท
Infer<V> = V extends Validator<infer T> ? T : never — conditional + infer15
mapped type + key remapping (as ... ? K : never) แยก optional14
const type parameter (literal<const T extends ...>)37
discriminated union ParseResult<T> (.success)7, 12
type guard (x): x is ValidationIssue ใน filter23, 28
Prettify<T> — mapped type ทำ hover สวย14
expectTypeOf type-level test34

ต่อยอด

  • array(inner), boolean(), union(...), record(inner)
  • .transform((v) => ...) — แปลงค่าหลัง validate
  • .refine((v) => bool, msg) — custom check
  • .default(value) — ค่าเริ่มต้น
  • แต่จริง ๆ ใช้ zod — โปรเจกต์นี้เพื่อเข้าใจกลไก ไม่ใช่แทน zod

เรื่องที่คนมักพลาด

  • _type มีค่าจริง — เป็น phantom type; ใช้แค่ infer ใน Infer<V> (ค่าไม่สำคัญ)
  • infer optional key ผิด — ต้องใช้ undefined extends Infer<S[K]> + key remapping แยกเป็น 2 mapped type แล้ว &
  • ไม่ Prettify — hover แสดง InferObject<{...}> แทน type จริง
  • fluent API return validator ตัวเดียว — min().max() ต้อง return object เดิม (mutate checks array)
  • literal ไม่มี const — literal("a", "b") ได้ Validator<string> แทน Validator<"a" | "b">
  • stop ที่ error แรก — รวม issue จากทุก field ให้ผู้ใช้เห็นครบ (เหมือน zod)

สรุป

  • Infer<V> = V extends Validator<infer T> ? T : never — ดึง type จาก validator (phantom _type)
  • object → type: mapped type + key remapping แยก optional (undefined extends Infer<S[K]> ? K : never) แล้ว &
  • fluent API (string().min(3).email()) — return validator เดิม, push check เข้า array
  • literal<const T>(...) — const type param ให้ได้ union ของ literal
  • ParseResult<T> = discriminated union — รวม issue จากทุก field (ไม่ stop ที่ error แรก)
  • ใช้ zod จริง — นี่คือการเรียนกลไก

บทสุดท้าย โปรเจกต์ React แอปเล็ก — typed props/hooks/context/API ครบ