Reputation: 1968
Need to create some factory method inside Angular 5 service based on generic type T passed to this service. How to get name of generic type "T"?
@Injectable()
export class SomeService<T> {
someModel: T;
constructor(protected userService: UserService) {
let user = this.userService.getLocalUser();
let type: new () => T;
console.log(typeof(type)) // returns "undefined"
console.log(type instanceof MyModel) // returns "false"
let model = new T(); // doesn't compile, T refers to a type, but used as a value
// I also tried to initialize type, but compiler says that types are different and can't be assigned
let type: new () => T = {}; // doesn't compile, {} is not assignable to type T
}
}
// This is how this service is supposed to be initialized
class SomeComponent {
constructor(service: SomeService<MyModel>) {
let modelName = this.service.getSomeInfoAboutInternalModel();
}
}
Upvotes: 2
Views: 9460
Reputation: 18292
You cannot instantiate a class based on generic types only.
I mean, if you want this:
function createInstance<T>(): T {...}
It is not possible, because, it would transpile into this:
function createInstance() {...}
Which, as you can see, cannot be parametrized in any way.
The closest you can get to what you want is this:
function createInstance<T>(type: new() => T): T {
return new type();
}
Then, if you have a class with a parameterless constructor:
class C1 {
name: string;
constructor() { name = 'my name'; }
}
You can now do this:
createInstance(C1); // returns an object <C1>{ name: 'my name' }
This works perfectly and the compiler gives you correct type information.
The reason I'm using new() => T
as the type for type
, is to indicate that you must pass a constructor function with no parameters that must return a type T. The class itself is exactly that. In this case, if you have
class C2 {
constructor(private name: string) {}
}
And you do
createInstance(C2);
the compiler will throw an error.
You can, however, generalise the createInstance
function so it works for objects with any number of parameters:
function createInstance2<T>(type: new (...args) => T, ...args: any[]): T
{
return new type(...args);
}
Now:
createInstance(C1); // returns <C1>{ name: 'my name'}
createInstance(C2, 'John'); // returns <C2>{name: 'John'}
I hope this serves you.
Upvotes: 6
Reputation: 1467
Genrics are used for type validation
class Array<T>{
pop:() => T;
unshift:(v:T) => void;
}
let numbers: Array<number> = ['1212']; //error
let strings: Array<string> = ['1','2','3']; //work
class Product{
}
let products: Array<Product> = [new Product(), new Product()]; //works
Upvotes: 1