我使用Constrained Mixins,当我试图访问test()函数中未定义的属性a时,没有引发错误,它应该引发错误TS2339: Property  a  does not exist on type  A,为什么不发生呢?

export function withBindable<T extends new (...args: any[]) => any>(BaseType: T) {
    return class extends BaseType {
        public mixin = 1;
    };
}

class Base{
    public b = 2;
}

class A extends withBindable(Base){
    public test(){
        this.mixin = 2; // OK
        this.b = 3; // OK
        this.a = 2; // should raise an error, but no error raised, tsc will compile this code successfully, and typeof this.a is any 
    }
}

推荐答案

这个问题被报告为microsoft/TypeScript#33943,但它从未被归类为错误、设计限制或故意 Select .在这个问题中,假设当基构造函数的generic constraint的实例类型为the unsound any type时,这似乎是一个问题.假设是这样的话,您可以通过将any替换为object(或者可能是另一个声音超类型,如{})来纠正该问题:

export function withBindable<T extends new (...args: any[]) => object>(BaseType: T) {
    return class extends BaseType {
        public mixin = 1;
    };
}

class Base{
    public b = 2;
}

class A extends withBindable(Base){
    public test(){
        this.mixin = 2; // OK
        this.b = 3; // OK
        this.a = 2; // error, as expected
    }
}

尽管如此,目前的行为似乎是不受欢迎的,所以如果这个问题得到官方诊断就好了.

Playground link to code

Typescript相关问答推荐

如何根据参数的值缩小函数内的签名范围?

为什么在TypScript中写入typeof someArray[number]有效?

在类型内部使用泛型类型时,不能使用其他字符串索引

TypeScript Page Routing在单击时不呈现子页面(React Router v6)

为什么从数组中删除一个值会删除打字错误?

为什么tsx不判断名称中有"—"的属性?'

有没有办法解决这个问题,类型和IntrinsicAttributes类型没有相同的属性?

在映射类型中用作索引时,TypeScrip泛型类型参数无法正常工作

向NextAuth会话添加除名称、图像和ID之外的更多详细信息

为什么不能使用$EVENT接收字符串数组?

如何从MAT-FORM-FIELD-MAT-SELECT中移除焦点?

React router 6(数据路由)使用数据重定向

无法将从服务器接收的JSON对象转换为所需的类型,因此可以分析数据

为什么S struct 类型化(即鸭子类型化)需要非严格类型联合?

Typescript -返回接口中函数的类型

tailwind css未被应用-react

在Thunk中间件中输入额外参数时Redux工具包的打字脚本错误

在Google授权后由客户端接收令牌

TypeScrip:从嵌套的对象值创建新类型

Typescript 从泛型推断类型