类实例非对象的typescript约束

类实例非对象的typescript约束,typescript,Typescript,不确定这是否可能,但可能在typescript中有一种方法可以仅为类实例而不是对象实现类型约束。 要使以下示例成为可能: class EmptyClass {} class ClassWithConstructorParams { constructor (public name: string) {} } function theFunction<SomeConstraint>(arg: SomeConstraint): void { // todo: do s

不确定这是否可能,但可能在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
class EmptyClass{}
类的构造函数参数{
构造函数(公共名称:字符串){}
}
函数函数(arg:SomeConstraint):void{
//托多:做点什么
}
函数(new EmptyClass());//应该可以
函数(带有构造函数参数('foo')的新类);//应该可以
函数({})//应该是编译错误
函数({name:'foo'});//应该是编译错误
//显然,还应该防止数字、字符串、委托等
函数(“”);//应该是编译错误
函数(1);//应该是编译错误
函数(清空类);//应该是编译错误
函数(函数);//应该是编译错误
到目前为止,我管理了一个只允许实例的过滤器,但它同时接受类实例和对象{}。需要防止物体移动


提前感谢

没有一般的方法可以做到这一点,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
类EmptyClass{
私有结构:未定义
}
类ClassWithConstructorParams扩展EmptyClass{
构造函数(公共名称:字符串){
超级()
}
}
另一类{
私有结构:未定义
}
函数theFunction(arg:T):void{
//托多:做点什么
}
//.建造师
函数(new EmptyClass());//应该可以
函数(带有构造函数参数('foo')的新类);//应该可以
函数(new OtherClass())//错误不是同一个私有字段
函数({notStructural:undefined})//错误
函数({})//错误
函数({name:'foo'});//错误
是的,我就是这么想的(关于不可能)。