特定の文字列を含む配列やオブジェクトについて、as const
をつけることで型エラーを解決できる場合があります。
例
const fruit = {
name: "apple",
color: "red",
};
function printFruit(fruit: { name: "apple"; color: "red" }) {
console.log(`name: ${fruit.name}, color: ${fruit.color}`);
}
printFruit(fruit); // エラー: 引数の型が一致しない
const fruit = {
name: "apple",
color: "red",
} as const;
function printFruit(fruit: { name: "apple"; color: "red" }) {
console.log(`name: ${fruit.name}, color: ${fruit.color}`);
}
printFruit(fruit);
なぜこうなった?
TypeScript の as const
は不変な値を示す型アサーションです。
as const
を使用せずに配列やオブジェクトを定義した場合、その値はあとから変更されることを想定してリテラル型としてではなくより一般的な型( string
や number
など)に推論されます。
一方で as const
を使用した場合は変更しないことを明示するため、リテラル型として推論されます。
なので、特定の値を持つことが要求される場面では as const
を使用することで型エラーを回避する事ができます。