TypeScriptのas constとsatisfiesはそれぞれ異なる機能を持つが、併用するとどういうメリットがあるのか調べた
まずそれぞれの機能について
as const
通常のリテラル値は広い型(例えばstringやnumber)に推論されるが、as constを使うと「リテラル型」として固定される
例えば
const example = { name: "John", age: 30, } as const; // 推論結果 // const example: { // readonly name: "John"; // readonly age: 30; // }
as constを使うとすべてのプロパティがリードオンリーになり、値自体も変更不可になる
satisfies
satisfiesはTypeScript 4.9以降で利用可能な構文で、指定された型に完全に一致するようにすることができる
つまり、余計なプロパティが含まれているとエラーになる
例えば
type Person = { name: string; age: number; }; const person = { name: "Alice", age: 25, address: "Wonderland", } satisfies Person;
型Personに必要なプロパティ(nameとage)が存在することを確認
ただし、型チェックの対象外であるプロパティ(address)でエラーになる
as constとsatisfiesの併用
併用することで、リテラル型の制約と型チェックの両方を活用できる
例えば
type ButtonConfig = { size: "small" | "medium" | "large"; color: "red" | "blue" | "green"; }; const config = { size: "small", color: "red", } as const satisfies ButtonConfig; // 推論結果 // const config: { // readonly size: "small"; // readonly color: "red"; // }
これによりas constでリテラル型("small"、"red")として固定しつつ、satisfiesにより、型ButtonConfigに一致するかどうかをチェックすることができる