TypeScript の 条件型

レベル 4238 打鍵

条件型はextendsを使用して条件に基づいて型を選択します。

TypeScript のコード

// Tがstringに代入できれば "yes"、そうでなければ "no" になる型です
1type IsString<T> = T extends string ? "yes" : "no";
// stringはstringに代入できるので、Aは "yes" です
2type A = IsString<string>;
// numberはstringに代入できないので、Bは "no" です
3type B = IsString<number>;
// Aはリテラル型 "yes" なので、代入できるのは "yes" だけです
4const resultA: A = "yes";
// 同様に、Bには "no" しか代入できません
5const resultB: B = "no";
// 「String check: yes」と表示します
6console.log(`String check: ${resultA}`);
// 「Number check: no」と表示します
7console.log(`Number check: ${resultB}`);

実行結果

String check: yes
Number check: no
このコードでタイピング練習する

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

このコードで使う記号

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

  • "× 8
  • ;× 7
  • :× 5
  • =× 5
  • `× 4
  • <× 3
  • >× 3
  • .× 2
  • (× 2
  • )× 2

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

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