February 2019
Beginner
694 pages
18h 4m
English
From time to time, generic classes may need to create an object of the type that is passed in as the generic type T. Consider the following code:
class FirstClass {
id: number | undefined;
}
class SecondClass {
name: string | undefined;
}
class GenericCreator< T > {
create(): T {
return new T();
}
}
var creator1 = new GenericCreator<FirstClass>();
var firstClass: FirstClass = creator1.create();
var creator2 = new GenericCreator<SecondClass>();
var secondClass : SecondClass = creator2.create();
Here, we have two class definitions, FirstClass and SecondClass. FirstClass just has a public id property, and SecondClass has a public name property. We then have a generic class that accepts a type T and has ...
Read now
Unlock full access