【发布时间】:2018-08-31 01:23:28
【问题描述】:
需要基于传递给该服务的泛型类型 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();
}
}
【问题讨论】:
-
也许 instanceof 就是你要找的东西
-
console.log(typeof(type))返回 undefined 因为type是一个未初始化的变量。您必须记住,TypeScript 的类型注释在运行时会消失,因此,在运行时,您会这样做:console.log(typeof(undefined)),当然,它会返回undefined。 -
我提出了重复,因为它们是相同的。没有答案,因为没有实例就不可能在运行时进行。
标签: angular typescript