TypeScript の アサーション関数

レベル 5508 打鍵

アサーション関数の戻り値の型は asserts value is X の形をとります。例外を投げずに戻れば、TypeScript はそれ以降のコードで変数を X に絞り込みます。

TypeScript のコード

// これが正常に戻れば、それ以降 value は string になる
1function assertIsString(value: unknown): asserts value is string {
// string でなければ、実際の型を示して例外を投げる
2 if (typeof value !== "string") {
3 throw new Error(`Expected string, got ${typeof value}`);
4 }
5}
// ジェネリック版: T から null と undefined を取り除く
6function assertDefined<T>(value: T): asserts value is NonNullable<T> {
// null か undefined なら例外を投げる
7 if (value === null || value === undefined) {
8 throw new Error("Value must be defined");
9 }
10}
// unknown なので、絞り込む前はメソッドを呼べない
11const data: unknown = "Hello, TypeScript!";
// チェックを通るので data は string に絞り込まれる
12assertIsString(data);
// これで toUpperCase を呼べる。「HELLO, TYPESCRIPT!」を表示する
13console.log(data.toUpperCase());
14const maybe: string | null = "World";
// string | null を string に絞り込む
15assertDefined(maybe);
// length を安全に読める。5 を表示する
16console.log(maybe.length);

実行結果

HELLO, TYPESCRIPT!
5
このコードでタイピング練習する

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

このコードで使う記号

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

  • (× 11
  • )× 11
  • =× 10
  • ;× 8
  • "× 8
  • :× 6
  • {× 5
  • }× 5
  • .× 4
  • |× 3

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

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