需要在Angular 5服务中基于传递给此服务的泛型类型T创建一些工厂方法。如何获得泛型类型“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();
}
}
答案 0 :(得分:3)
您不能仅基于泛型类型实例化类。
我的意思是,如果你想要这个:
function createInstance<T>(): T {...}
这是不可能的,因为它会转变为:
function createInstance() {...}
正如您所看到的,无法以任何方式进行参数化。
最接近你想要的是:
function createInstance<T>(type: new() => T): T {
return new type();
}
然后,如果你有一个带无参数构造函数的类:
class C1 {
name: string;
constructor() { name = 'my name'; }
}
您现在可以执行此操作:
createInstance(C1); // returns an object <C1>{ name: 'my name' }
这非常有效,编译器会为您提供正确的类型信息。
我使用new() => T
作为type
类型的原因是为了表明你必须传递一个没有必须返回类型T的参数的构造函数。类本身就是这样。在这种情况下,如果你有
class C2 {
constructor(private name: string) {}
}
你做了
createInstance(C2);
编译器会抛出错误。
但是,您可以概括createInstance
函数,以便它适用于具有任意数量参数的对象:
function createInstance2<T>(type: new (...args) => T, ...args: any[]): T
{
return new type(...args);
}
现在:
createInstance(C1); // returns <C1>{ name: 'my name'}
createInstance(C2, 'John'); // returns <C2>{name: 'John'}
我希望这能为你服务。
答案 1 :(得分:1)
Genrics用于类型验证
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