LoginSignup
0
0

More than 5 years have passed since last update.

コンストラクタが同じクラスなら何でもnewできる関数の作り方

Posted at

コンストラクタのシグネチャが同じクラスなら何でもnewできる関数を作るにはジェネリクスを使う。

大まかな流れ:

  1. コンストラクタのシグネチャを定義した型を宣言する
  2. その型を関数の引数にする

サンプルコード:

// 引数がゼロのコンストラクタを持つクラスの型を定義する
type NoParameterConstructor<A> = new () => A

// 同じコンストラクタを持つクラスならnewできる関数
function create<A>(a: NoParameterConstructor<A>): A {
  return new a()
}

// NoParameterConstructorを満たすクラス(つまり同じコンストラクタを持つ)
class ClassA {}
class ClassB {}

console.log(create(ClassA), create(ClassB))
実行結果
ClassA {} ClassB {}

ちなみに、次のどちらかの方法でインラインで宣言しても良い

function create<A>(a: new () => A): A {
  return new a()
}

function create<A>(a: { new (): A }): A {
  return new a()
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0