[英]How to get name of generic type T inside service in Angular
需要基于传递给该服务的通用类型T在Angular 5服务中创建一些工厂方法。 如何获得通用类型“ 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();
}
}
您不能仅基于泛型类型实例化一个类。
我的意思是,如果您想要这样做:
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的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'}
希望这对您有帮助。
泛型用于类型验证
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.