🔒

TypeScriptにおける as const とは

に公開

as const とは?

TypeScriptにおける アサーション(型強制) の一種。
これを使用すると、オブジェクトや配列の各要素が 「リテラル型」 として扱われ、さらに全てのプロパティが readonly となる。

リテラル型とは

「string」「number」などの一般的なデータ型ではなく、 特定の値(リテラル)そのものを型として扱う もの

a.文字列リテラル型

Direction 型は string 型なのではなく、具体的に "left" or "right" しか受け付けないので、"up" を代入しようとするとエラーになる

type Direction = "left" | "right"
let direction: Direction;

direction = "left"
direction = "right"
direction = "up" // error

b. 数値リテラル型

Count 型は number 型なのではなく、具体的に 1 or 2 or 3 しか受け付けないので、4 を代入しようとするとエラーになる

type Count = 1 | 2 | 3
let count: Count;

count = 1; 
count = 2; 
count = 4; // error

c. 真偽値リテラル型

Enabled 型は boolean 型なのではなく、具体的に true しか受け付けないので、false を代入しようとするとエラーになる

type Enabled: true;
let isEnabled: Enabled;
isEnabled = true;
isEnabled = false; // error

as const を使わない場合

const fruits = {
  apple: "apple",
  orange: "orange",
  banana: "banana",
};

TypeScript の型推論ではそれぞれのフィールドが string型となる。

したがって、以下のような代入をしてもエラーにならない

fruits.apple = "dog";

as const を使う場合

const fruits = {
  apple: "apple",
  orange: "orange",
  banana: "banana",
} as const;

TypeScript の型推論ではそれぞれのフィールドが具体的なリテラル型となる。

さらに、それぞれ readonly となり変更が不可になるため、値を代入しようとするとエラーになる

Discussion