TypeScript contracts

← 开发理念

文章目前提供英语和俄语版本。以下显示英语版本。

Express valid states

Prefer type, unknown, as const, discriminated unions and satisfies. Validate external data at runtime through the project's existing validation mechanism. A cast does not validate an API response.

type TResult<TData> =
    | { ok: true, data: TData }
    | { ok: false, status: number, message: string }

const render_result = (result: TResult<string>) => {
    if (!result.ok) return result.message
    return result.data
}

Use never for exhaustiveness and typed registries for mappings. Avoid any, artificial generics and abstractions created only for type-system aesthetics. A public type belongs to the module that owns the contract.