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); 

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.