設定オブジェクトに型を付けるとき、型注釈を書くとリテラル型の推論が消えてしまいます。satisfies を使うと、型チェックはしつつ推論結果をそのまま残せます。
型注釈の場合
type Route = { path: string; auth: boolean };
const routes: Record<string, Route> = { home: { path: '/', auth: false }, admin: { path: '/admin', auth: true },};
routes.home; // Routeroutes.typo; // エラーにならないRecord<string, Route> と注釈したので、存在しないキーにアクセスしてもエラーになりません。
satisfies の場合
const routes = { home: { path: '/', auth: false }, admin: { path: '/admin', auth: true },} satisfies Record<string, Route>;
routes.home; // { path: string; auth: boolean }routes.typo; // エラー: Property 'typo' does not exist値が Route の形になっているかはチェックされ、キーの一覧は推論されたまま残ります。
使い分け
- 外部に公開する関数の引数や戻り値には 型注釈
- 自分で書く設定オブジェクトや定数テーブルには satisfies
asは型チェックを弱めるので、最後の手段にする