Creating Generic Types

Given the following class:

class Datum {} 

I get an error ( error TS2304: Cannot find name 'T' ) when I try to do the following:

 class Data<T extends Datum> { datum: T constructor() { this.datum = new T() } } 

So, I try to do this, but also get an error ( Type 'Datum' is not assignable to type 'T' ):

  class Data<T extends Datum> { datum: T constructor() { this.datum = new Datum(); } } 

Question: Is it not possible to instantiate a restricted type T? My assumption was that since T is limited to such that it must expand with Datum , I could do datum: T = new Datum() .

+5
source share
1 answer

Two things to remember: firstly, generic files are erased at compile time. They have no impact at run time, so any attempt to refer to a generic type as a run-time value does not make sense.

Secondly, it is possible for the Datum derived class to have constructor parameters. Even if T really exists, you can just blindly new with null arguments.

Combining this, you want the following:

 class Datum {} class Data<T extends Datum> { datum: T constructor(ctor: new() => T) { this.datum = new ctor(); } } class ByteDatum extends Datum { new() { } } let y = new Data(ByteDatum); let x = y.datum; // x: ByteDatum 
+6
source

All Articles