0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

特定の文字列を含む配列、オブジェクトの型エラーを解決する【as const】

Last updated at Posted at 2025-03-25

特定の文字列を含む配列やオブジェクトについて、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 を使用せずに配列やオブジェクトを定義した場合、その値はあとから変更されることを想定してリテラル型としてではなくより一般的な型( stringnumber など)に推論されます。

一方で as const を使用した場合は変更しないことを明示するため、リテラル型として推論されます。

なので、特定の値を持つことが要求される場面では as const を使用することで型エラーを回避する事ができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?