You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript类型不满足typeof AbstractBodyWithTabs约束问题求解

问题根因

之前的报错本质是typeof AbstractBodyWithTabs是未绑定泛型参数的抽象类构造类型,它的泛型T、U属于开放类型,TS无法确认具体的TestBody构造签名能兼容所有可能的T、U子类型约束,因此抛出不匹配错误。

最简解决方案

直接将PageWithTabs的泛型约束改为实例类型而非构造函数类型,仅需要1个泛型参数,无需重复传入已在TestBody中声明的关联类型:

第一步:修改PageWithTabs定义

export abstract class PageWithTabs<V extends AbstractBodyWithTabs<any, any>> {
    abstract get body () : V
    get footer () {
        return new SaveAndCancelFooter();
    }
    get header () {
        return new Header();
    }
}

第二步:修改TestPage继承声明

class TestPage extends PageWithTabs<TestBody> {
    get body () {
        return new TestBody();
    }
}

扩展:如果需要在PageWithTabs中提取关联的内容、标签类型

可以通过条件类型自动从传入的V泛型中提取对应的T、U类型,无需额外传参:

// 定义提取工具类型
type ExtractContent<T extends AbstractBodyWithTabs<any, any>> = T extends AbstractBodyWithTabs<infer C, any> ? C : never
type ExtractTabs<T extends AbstractBodyWithTabs<any, any>> = T extends AbstractBodyWithTabs<any, infer U> ? U : never

// 在PageWithTabs中使用
export abstract class PageWithTabs<V extends AbstractBodyWithTabs<any, any>> {
    abstract get body () : V
    get footer () {
        return new SaveAndCancelFooter();
    }
    get header () {
        return new Header();
    }
    // 示例:返回类型自动绑定为TestContent
    getContents(): ExtractContent<V> {
        return this.body.contents
    }
    // 示例:返回类型自动绑定为TestTabs
    getTabs(): ExtractTabs<V> {
        return this.body.tabs
    }
}

内容的提问来源于stack exchange,提问作者A. L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:54:07