TypeScript の InstanceType ユーティリティ型
レベル 4334 打鍵
InstanceType ユーティリティ型はコンストラクタ関数のインスタンス型を抽出します。
TypeScript のコード
// Userクラスを定義する1class User { // public付きのパラメータでnameとageプロパティを作って代入する2 constructor(public name: string, public age: number) {} // 挨拶を返すメソッド3 greet(): string { // インスタンスのnameを使って挨拶を作る4 return `Hello, I'm ${this.name}`;5 }6}// InstanceType で new User(...) が作るオブジェクトの型(つまりUser)を得る7type UserInstance = InstanceType<typeof User>;// クラスそのもの(typeof User)を受け取り、インスタンスを返す8function createAndGreet(UserClass: typeof User): UserInstance { // 渡されたクラスでインスタンスを作る9 return new UserClass("Alice", 30);10}// Userクラスそのものを引数として渡す11const user = createAndGreet(User);// 「Hello, I'm Alice」と表示する12console.log(user.greet());実行結果
Hello, I'm Alice
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
(× 7)× 7;× 5:× 5{× 5}× 5,× 3.× 3"× 2`× 2