我正在尝试使用TypeScript创建服务存储库。
我正在尝试确定是否已注册指定类型的服务实例。这是一个例子(假设接口存在):
class ServiceRepository {
static RegisteredServices: Array<IService> = new Array<IService>();
static Register<T extends IService>(service: T) {
// Does a registered service already exist?
var existingService = this.RegisteredServices.filter(
function (item: IService) {
return (item instanceof T); // <--------------------- How do we compare Types?
});
if (existingService != null) {
// Remove it first.
this.RegisteredServices.splice(this.RegisteredServices.indexOf(existingService), 1);
}
// Add new service instance.
this.RegisteredServices.push(service);
}
}
如何比较Item的类型和泛型类型T?
答案 0 :(得分:5)
类型在运行时在TypeScript中被擦除。所以你需要一些不依赖于类型的运行时机制。这是一个检查类的名称属性的解决方案:
interface IService{}
class ServiceRepository {
static RegisteredServices: Array<IService> = new Array<IService>();
static Register<T extends IService>(service: T) {
// Does a registered service already exist?
var existingService = this.RegisteredServices.filter(
function(item: IService) {
return ((<any>item).name == (<any>service).name); // check
})[0];
if (existingService) {
// Remove it first.
console.log('removing:',existingService);
this.RegisteredServices.splice(this.RegisteredServices.indexOf(existingService), 1);
}
// Add new service instance.
this.RegisteredServices.push(service);
}
}
class Foo implements IService{}
ServiceRepository.Register(Foo);
ServiceRepository.Register(Foo);
name
是命名函数的属性,这是因为在TypeScript到JavaScript转换中实现类的方式。
此外,过滤功能的结果是一个数组。我为你修好了。