Ano*_*ous 1 typescript 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();
}
}
Run Code Online (Sandbox Code Playgroud)
不能仅基于泛型类型实例化类。
我的意思是,如果你想要这个:
function createInstance<T>(): T {...}
Run Code Online (Sandbox Code Playgroud)
这是不可能的,因为它会转化为:
function createInstance() {...}
Run Code Online (Sandbox Code Playgroud)
如您所见,不能以任何方式参数化。
最接近你想要的东西是这样的:
function createInstance<T>(type: new() => T): T {
return new type();
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您有一个带有无参数构造函数的类:
class C1 {
name: string;
constructor() { name = 'my name'; }
}
Run Code Online (Sandbox Code Playgroud)
你现在可以这样做:
createInstance(C1); // returns an object <C1>{ name: 'my name' }
Run Code Online (Sandbox Code Playgroud)
这非常有效,编译器会为您提供正确的类型信息。我使用new() => T作为 , 的类型的原因type是表明您必须传递一个没有必须返回类型 T 的参数的构造函数。类本身就是这样。在这种情况下,如果您有
class C2 {
constructor(private name: string) {}
}
Run Code Online (Sandbox Code Playgroud)
你也是
createInstance(C2);
Run Code Online (Sandbox Code Playgroud)
编译器会抛出错误。
但是,您可以概括该createInstance函数,使其适用于具有任意数量参数的对象:
function createInstance2<T>(type: new (...args) => T, ...args: any[]): T
{
return new type(...args);
}
Run Code Online (Sandbox Code Playgroud)
现在:
createInstance(C1); // returns <C1>{ name: 'my name'}
createInstance(C2, 'John'); // returns <C2>{name: 'John'}
Run Code Online (Sandbox Code Playgroud)
我希望这对你有用。
| 归档时间: |
|
| 查看次数: |
5573 次 |
| 最近记录: |