不确定是否有可能,但是在typescript中可能只对类实例而不对对象实现类型约束。 为了使下面的示例成为可能:
class EmptyClass {}
class ClassWithConstructorParams {
constructor (public name: string) {}
}
function theFunction<SomeConstraint>(arg: SomeConstraint): void {
// todo: do something
}
theFunction(new EmptyClass()); // should be OK
theFunction(new ClassWithConstructorParams('foo')); // should be OK
theFunction({}) // should be COMPILE ERROR
theFunction({name:'foo'}); // should be COMPILE ERROR
// obviously should also prevent numbers, string, delegates and etc
theFunction(''); // should be COMPILE ERROR
theFunction(1); // should be COMPILE ERROR
theFunction(EmptyClass); // should be COMPILE ERROR
theFunction(theFunction); // should be COMPILE ERROR
到目前为止,我已经管理了一个仅允许实例的过滤器,但是它同时接受类实例和对象{}。需要防止物体。
预先感谢
答案 0 :(得分:0)
没有通用的方法,Typescript使用结构化类型,并且只要对象文字满足函数的约束,它将作为参数有效。
如果要传递给该函数的类具有公共基类,则可以向其添加私有字段。除了从该类派生的类,其他任何类或对象文字都无法满足具有私有字段的类的约束。
class EmptyClass {
private notStructural: undefined
}
class ClassWithConstructorParams extends EmptyClass {
constructor(public name: string) {
super()
}
}
class OtherClass{
private notStructural: undefined
}
function theFunction<T extends EmptyClass>(arg: T): void {
// todo: do something
}
//.constructor
theFunction(new EmptyClass()); // should be OK
theFunction(new ClassWithConstructorParams('foo')); // should be OK
theFunction(new OtherClass()) // error not the same private field
theFunction({ notStructural: undefined }) // error
theFunction({}) // ERROR
theFunction({name:'foo'}); // ERROR