大家好,我正在为名为InversifyJS 的TypeScript 应用程序开发 IoC 容器。 我实现了一个名为TypeBinding<TServiceType>
,它用于定义service type
(接口)和implementation type
(类)之间的绑定。 类代码如下:
// Defines allowed scope modes
enum TypeBindingScopeEnum {
Transient,
Singleton
}
class TypeBinding<TServiceType> {
// The runtime identifier used because at runtime
// we don't have interfaces
public runtimeIdentifier : string;
// The constructor of a class that must implement TServiceType
public implementationType : { new(): TServiceType ;};
// Cache used to allow singleton scope
public cache : TServiceType;
// The scope mode to be used
public scope : TypeBindingScopeEnum;
constructor(
runtimeIdentifier : string,
implementationType : { new(): TServiceType ;},
scopeType? : TypeBindingScopeEnum) {
this.runtimeIdentifier = runtimeIdentifier;
this.implementationType = implementationType;
this.cache = null;
if(typeof scopeType === "undefined") {
// Default scope is Transient
this.scope = TypeBindingScopeEnum.Transient;
}
else {
if(TypeBindingScopeEnum[scopeType]) {
this.scope = scopeType;
}
else {
var msg = `Invalid scope type ${scopeType}`;
throw new Error(msg);
}
}
}
}
我定义了一些实体来测试TypeBinding<TServiceType>
类:
interface FooInterface {
logFoo() : void;
}
interface BarInterface {
logBar() : void;
}
interface FooBarInterface {
logFooBar() : void;
}
// Notice default constructor
class Foo implements FooInterface {
public logFoo(){
console.log("foo");
}
}
// Notice default constructor
class Bar implements BarInterface {
public logBar(){
console.log("bar");
}
}
// Notice dependencies on FooInterface and BarInterface on constructor
class FooBar implements FooBarInterface {
public foo : FooInterface;
public bar : BarInterface;
public logFooBar(){
console.log("foobar");
}
constructor(FooInterface : FooInterface, BarInterface : BarInterface) {
this.foo = FooInterface;
this.bar = BarInterface;
}
}
我可以使用TypeBinding<TServiceType>
类,而Foo
和Bar
类没有问题
var fooBinding = new TypeBinding<FooInterface>("FooInterface", Foo);
var barBinding = new TypeBinding<BarInterface>("BarInterface", Bar);
当我尝试使用{ new(): TServiceType ;}
并且实现TServiceType
的类的构造函数不是无参数时,我的问题就出现了。
“typeof FooBar”类型的参数不可分配给“new () => FooBarInterface”类型的参数。
var fooBarBinding = new TypeBinding<FooBarInterface>("FooBarInterface", FooBar);
如何解决这个问题?
谢谢 :)
我想我已经通过更改类属性解决了这个问题:
implementationType : { new(): TServiceType ;},
到:
implementationType : { new(...args : any[]): TServiceType ;},
会写一些单元测试来确认。
谢谢...
聪明的! 谢谢你的花絮:)
感谢这一点,我正在寻找一种方法来对传入函数参数的构造函数执行类型检查。 { new(...args : any[]): T ;}
允许我这样做。
这意味着我可以对装饰器目标执行类型检查
function decor(oPar: {}): <TFunc extends { new (...args: any[]): A }>(target: TFunc) => void {
return function <TFunc extends { new (...args: any[]): A }>(target: TFunc): void {
console.log(oPar, target);
}
}
class A { id: string; }
// will error
@decor({})
class B { }
// Works
@decor({})
class C extends A { }
最有用的评论
我想我已经通过更改类属性解决了这个问题:
到:
会写一些单元测试来确认。
谢谢...