実践パターン集 — よくある型の書き方
この章は逆引きリファレンスです。「こういうことがしたいとき、型をどう書くか」を場面ごとにまとめます。
学習者やりたいことは分かってるのに、型の書き方だけ思い出せない…ってよくあるんだよね。
掲載予定のパターン
APIレスポンスの型定義
type ApiResponse<T> = {
data: T;
meta: { total: number; page: number };
};
type ErrorResponse = {
error: { code: string; message: string };
};
type ApiResult<T> = ApiResponse<T> | ErrorResponse;フォームの状態管理
複数フィールドを持つフォームのstate型と、フィールドごとの更新関数の型。
環境変数の型付け
process.env の型を安全に扱う方法。global.d.ts での型拡張パターン。
配列から型を抽出する
const statuses = ['loading', 'success', 'error'] as const;
type Status = (typeof statuses)[number];
// 'loading' | 'success' | 'error'オブジェクトのキーから型を作る
const routes = {
home: '/',
about: '/about',
contact: '/contact',
} as const;
type RouteName = keyof typeof routes;
// 'home' | 'about' | 'contact'条件付きの型(Conditional Types)
type IsString<T> = T extends string ? true : false;高度なトピックだが、ライブラリの型定義を読むときに必要になる場面がある。
Mapped Types
type Optional<T> = {
[K in keyof T]?: T[K];
};ユーティリティ型の内部で使われている仕組み。Partialの自作例として解説予定。
Template Literal Types
type EventName = `on${Capitalize<string>}`;型の網羅性チェックのパターン集
判別可能なユニオンとswitch文の組み合わせバリエーション。
この章のパターンは随時追加していきます。「こういう場面の書き方を知りたい」というリクエストがあればお寄せください。