SuperAPI AI Directory

functional-ts

Coding & development

View repository

Updated 10-15 20:06

About this skill

Functional Domain Modeling in TypeScript

Principles for writing domain models in server-side TypeScript. Rather than class-based OOP, adopt a functional approach that makes the most of TypeScript's type system.

1. Domain modeling with types

Express state with Discriminated Unions

Define the state of domain entities not with classes but with Discriminated Unions. Define each state as an individual type and make state-specific properties required.

// Good: 各状態が独立した型。状態固有のプロパティが必須
type Waiting = Readonly<{
  kind: "Waiting";
  passengerId: PassengerId;
}>;

type EnRoute = Readonly<{ kind: "EnRoute"; passengerId: PassengerId; driverId: DriverId; }>;

type TaxiRequest = Waiting | EnRoute | InTrip | Completed | Cancelled;


```typescript
// Bad: optional プロパティで全状態を1つの型に押し込む
type TaxiRequest = {
  state: string;
  passengerId: string;
  driverId?: string;    // どの状態で存在するか不明
  startTime?: Date;     // null チェックが至る所で必要
  endTime?: Date;
};

Rationale: Optional properties cannot guarantee at compile time which properties exist in which state. With a Discriminated Union, once you discriminate the kind in a switch statement, you can safely access state-specific properties.

discriminantは kind and standardize on it

Across the entire project, standardize on kind as the discriminant property name.type, status, state etc. being mixed in undermines the consistency of the codebase.

Companion Object pattern

Group type definitions and related functions into an object with the same name.

type TaxiRequest = Waiting | EnRoute | InTrip | Completed | Cancelled;

const TaxiRequest = {
  assignDriver: (waiting: Waiting, driverId: DriverId): EnRoute => ({
    kind: "EnRoute",
    passengerId: waiting.passengerId,
    driverId,
  }),

  startTrip: (enRoute: EnRoute, startTime: Date): InTrip => ({
    kind: "InTrip",
    passengerId: enRoute.passengerId,
    driverId: enRoute.driverId,
    startTime,
  }),

  isActive: (request: TaxiRequest): request is Waiting | EnRoute | InTrip =>
    request.kind !== "Completed" && request.kind !== "Cancelled",
} as const;

type (useinterface rather than)

Define domain types with type .interface declaration merging carries the risk that merely declaring an interface with the same name in another file will implicitly change the shape of the type.

// Good
type User = Readonly<{
  id: UserId;
  name: string;
}>;

// Bad: 別ファイルで interface User { hashedPassword?: string } と宣言されると
// 気づかないうちに型が変わる
interface User {
  id: string;
  name: string;
}

Use function property notation (not method notation)

Write functions within type definitions using function property notation rather than method notation. Method notation makes parameter types bivariant and breaks type safety.

// Good: 関数プロパティ記法 — パラメータはcontravariant
type TaskRepository = {
  save: (task: Task) => Promise<void>;
  findById: (id: TaskId) => Promise<Task | undefined>;
};

// Bad: メソッド記法 — パラメータがbivariantになり、
// save(task: DoingTask) のような狭い実装が型チェックを通過してしまう
type TaskRepository = {
  save(task: Task): Promise<void>;
  findById(id: TaskId): Promise<Task | undefined>;
};

Distinguish meanings with Branded Types

Due to structural typing, string are mutually compatible. Apply Branded Types to IDs and values with different meanings.

declare const UserIdBrand: unique symbol;
type UserId = string & { readonly [UserIdBrand]: never };

declare const ProductIdBrand: unique symbol;
type ProductId = string & { readonly [ProductIdBrand]: never };

// UserId と ProductId は構造的に非互換になる

Readonly<> to guarantee immutability

Domain objects are Readonly<> and prevent reassignment of properties. Express state changes by creating new objects.

2. State transitions via functions

Express state transitions with pure functions. The function's argument type constrains the valid source states, and the return type makes the destination state explicit.

// assignDriver は Waiting 状態からのみ呼べる
const assignDriver = (waiting: Waiting, driverId: DriverId): EnRoute => ({
  kind: "EnRoute",
  passengerId: waiting.passengerId,
  driverId,
});

Invalid transitions (e.g., assignDriver(completed, driverId)) become compile errors. No runtime checks are needed.

Exhaustiveness checking

In switch statements, use assertNever to guarantee at compile time that all cases are handled. When a new state is added, unhandled locations are detected as compile errors.

const assertNever = (x: never): never => {
  throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
};

const describe = (request: TaxiRequest): string => {
  switch (request.kind) {
    case "Waiting": return "Waiting for driver";
    case "EnRoute": return `Driver ${request.driverId} en route`;
    case "InTrip": return "In trip";
    case "Completed": return "Completed";
    case "Cancelled": return "Cancelled";
    default: return assertNever(request);
  }
};

3. Error Handling — Railway Oriented Programming

Instead of throwing exceptions, treat errors as values using a Result type.

Library detection: of the project package.json の dependencies / devDependencies and follow the guide for the corresponding library. If neither is found, ask the user.

Define error types as Discriminated Unions so that callers can handle them exhaustively.

type AssignError =
  | Readonly<{ kind: "DriverNotAvailable"; driverId: DriverId }>
  | Readonly<{ kind: "RequestAlreadyAssigned" }>;

Express success and failure in types, and compose processing via chaining. For each library's API, refer to the guide above.

Details: error-handling.md

4. Defending the boundaries

External inputs (API requests, DB results, file reads) are runtime-validated with Zod schemas. Within the domain layer, types are trusted and excessive defensive validation is not performed.

import { z } from "zod";

const CreateRequestSchema = z.object({
  passengerId: z.string().uuid().transform(PassengerId.of),
});

// API handler
const handler = (req: Request) => {
  const result = CreateRequestSchema.safeParse(req.body);
  if (!result.success) return badRequest(result.error);
  // result.data は型安全。以降 as は不要
};

Do not use type assertions (as)

as bypasses type checking and causes runtime errors. Use Zod parsing for external data, and trust type inference for internal data.

PII protection

Apply the Sensitive<T> wrapper to fields containing personal information, and automatically mask them withJSON.stringify や console.log .

type Sensitive<T> = Readonly<{
  unwrap: () => T;
  toJSON: () => string;
  toString: () => string;
}>;

const Sensitive = {
  of: <T>(value: T): Sensitive<T> => ({
    unwrap: () => value,
    toJSON: () => "[REDACTED]",
    toString: () => "[REDACTED]",
    [Symbol.for("nodejs.util.inspect.custom")]: () => "[REDACTED]",
  }),
} as const;

Automatically wrap with a Zod schema.

const sensitiveString = z.string().transform(Sensitive.of);

const PatientSchema = z.object({
  name: sensitiveString,
  email: sensitiveString,
  role: z.string(), // PIIではないのでそのまま
});

Details: boundary-defense.md

5. Declarative style

Array operations

Write array transformations declaratively with filter / map / reduce . Define predicate functions in the Companion Object.

type Task = ActiveTask | CompletedTask;

const Task = {
  isActive: (task: Task): task is ActiveTask => task.kind === "Active",
} as const;

// 宣言的: 「何をしたいか」が明確
const activeTasks = tasks.filter(Task.isActive);

// 命令的: ループの中身を読まないと意図がわからない
const activeTasks: ActiveTask[] = [];
for (const task of tasks) {
  if (task.kind === "Active") activeTasks.push(task);
}

Domain events

Generate domain events accompanying state changes as immutable records, and record them separately from repositories.

type DomainEvent = Readonly<{
  eventId: string;
  eventAt: Date;
  eventName: string;
  payload: unknown;
  aggregateId: string;
}>;

Details: state-modeling.md

6. Test data

The test dummy data is as const satisfies Type for type-safe definition. The discriminant's literal type is preserved, preventing widening.

const waitingRequest = {
  kind: "Waiting",
  passengerId: "passenger-1" as PassengerId,
} as const satisfies Waiting;

// waitingRequest.kind は "Waiting" リテラル型(string ではない)

About applying the principles

These are recommendations, not strict rules. You may judge according to context, but when deviating from the principles, explicitly state the reason in a comment.

Typical valid reasons for deviation:

  • When an external library requires class inheritance
  • When performance requirements make the cost of generating immutable data a problem
  • When a different pattern has been adopted by team agreement