44
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

型定義で`typeof T`したくなった時は {new ():T}

Last updated at Posted at 2017-01-21

型定義でジェネリクスの型変数Tを使いつつ、インスタンス化する前のTそのもの1を定義するときのTIPS。

以前の記事で型クエリと組み合わせられたらなあ(typeof T)と書いていた。

同様に思う人は多かったらしく、いつの間にかTypeScriptの公式WIKIのFAQにやり方が書いてあった。
オブジェクトリテラル型の 型表現で {new ():T} とすればよい らしい。

function create<T>(ctor: { new(): T }) {
    return new ctor();
}
var c = create(MyClass); // c: MyClass

出典:Why can't I write typeof T, new T, or instanceof T in my generic function?

厳密にやるなら次のissueに紹介されていた方法もある。

/** Generic class type. */
type Constructor<T> = { new (...args: any[]): T } | ((...args: any[]) => T) | Function;

  1. 何と呼べばいいのか。

44
32
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
44
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?