TypeScript の as constアサーション

レベル 3305 打鍵

as constアサーションは値をreadonlyにし、型を広げずにリテラル型のまま保ちます。

TypeScript のコード

// 型はstring[]ではなくreadonly ["red", "green", "blue"]
1const colors = ["red", "green", "blue"] as const;
// numberで添字を取ると"red" | "green" | "blue"になる
2type Color = typeof colors[number];
// as constにより、各値は"/about"のようなリテラル型のまま
3const routes = {
4 home: "/",
5 about: "/about",
6 contact: "/contact"
// as constはすべてのプロパティもreadonlyにする
7} as const;
// すべての値のユニオン:"/" | "/about" | "/contact"
8type Route = typeof routes[keyof typeof routes];
// 3色のどれかでなければならない
9const myColor: Color = "red";
// 3つのルートのどれかでなければならない
10const myRoute: Route = "/about";
// 「red /about」を表示する
11console.log(myColor, myRoute);

実行結果

red /about
このコードでタイピング練習する

このコードでタイピング練習ができます。記録はランキングに反映されません。

このコードで使う記号

この TypeScript のコードで打つ記号と、出てくる回数です。

  • "× 16
  • ;× 7
  • =× 6
  • ,× 5
  • :× 5
  • /× 4
  • [× 3
  • ]× 3
  • .× 1
  • (× 1

TypeScript のレベル 3 のほかのコード例

← TypeScript タイピング練習のトップへ