Upgrade to Pro — share decks privately, control downloads, hide ads and more …

20250826 パターンマッチ

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for saka saka
December 24, 2025
3

20250826 パターンマッチ

Avatar for saka

saka

December 24, 2025

Transcript

  1. import { match } from "ts-pattern"; type Stationery = "Pen"

    | "Pencil"; const useSound = (item: Stationery) => { return match(item) .with("Pen", () => "Χνο") // ϊοΫࣜϖϯͷΠϝʔδ .with("Pencil", () => "αϥαϥ") // ॻ͖৺஍ͷΠϝʔδ .exhaustive(); // શͯͷύλʔϯ͕໢ཏ͞Ε͍ͯΔ͔νΣοΫ͢Δ }; useSound("Pen"); // "Χνο" useSound("Eraser"); // Type Error: '"Eraser"' is not assignable to type 'Stationery'
  2. import { match } from "ts-pattern"; type Stationery = "Pen"

    | "Pencil"; const useSound = (item: Stationery) => { return match(item) .with("Pen", () => "Χνο") // ϊοΫࣜϖϯͷΠϝʔδ .with("Pencil", () => "αϥαϥ") // ॻ͖৺஍ͷΠϝʔδ .exhaustive(); // શͯͷύλʔϯ͕໢ཏ͞Ε͍ͯΔ͔νΣοΫ͢Δ }; useSound("Pen"); // "Χνο" useSound("Eraser"); // Type Error: '"Eraser"' is not assignable to type 'Stationery'
  3. type Stationery = "Pen" | "Pencil"; const assertNever = (_:

    never): never => { throw new Error(); }; const check = (item: Stationery) => { switch (item) { case "Pen": return "Χνο"; case "Pencil": return "αϥαϥ"; default: return assertNever(item); } };
  4. type DogError = { kind: "DogError"; message: string; }; type

    CatError = { kind: "CatError"; message: string; }; type AnimalError = DogError | CatError;
  5. const checkAnimal = (animal: string): Result<string, AnimalError> => { if

    (animal === "Dogn") { return err({ kind: "DogError", message: "Invalid animal" }); } if (animal === "Catn") { return err({ kind: "CatError", message: "Invalid animal" }); } return ok("Animal"); };
  6. const result = checkAnimal("Dog"); result.match( (animal) => { console.log(animal); },

    (error) => { switch (error.kind) { case "DogError": return `DogError: ${error.message}`; case "CatError": return `CatError: ${error.message}`; default: return assertNever(error); } } );