- Learning TypeScript 2.x
- Remo H. Jansen
- 89字
- 2025-04-04 17:02:05
The new operator in generic types
To create a new object within a generic piece of code, we need to use the constructor function of the type. This means that instead of using t: T as follows:
function factory<T>(t: T) { return new t(); // Error }
We should use t: { new(): T;}, as follows:
function factory<T>(t: { new(): T }) { return new t(); } class Foo { public name!: "foo"; } class Bar { public name!: "bar"; } const foo = factory<Foo>(Foo); const bar = factory<Bar>(Bar);