TypeScript の ConstructorParameters ユーティリティ型

レベル 4319 打鍵

ConstructorParameters ユーティリティ型はコンストラクタからパラメータの型を抽出します。

TypeScript のコード

// Pointクラスを定義する
1class Point {
// 3つのpublicパラメータがx、y、labelプロパティになる
2 constructor(public x: number, public y: number, public label: string) {}
// 点を表示するメソッド
3 display(): void {
// ラベルに続けて座標を表示する
4 console.log(`${this.label}: (${this.x}, ${this.y})`);
5 }
6}
// ConstructorParameters でコンストラクタのパラメータ型 [number, number, string] を取り出す
7type PointParams = ConstructorParameters<typeof Point>;
// コンストラクタの引数を順に並べたタプル
8const params: PointParams = [10, 20, "Origin"];
// タプルを展開して new Point(10, 20, "Origin") を呼ぶ
9const point = new Point(...params);
// 「Origin: (10, 20)」と表示する
10point.display();

実行結果

Origin: (10, 20)
このコードでタイピング練習する

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

このコードで使う記号

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

  • .× 8
  • :× 6
  • (× 6
  • )× 6
  • {× 6
  • }× 6
  • ,× 5
  • ;× 5
  • =× 3
  • $× 3

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

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