April 2018
Beginner
536 pages
13h 21m
English
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);