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

使用泛型时对象无法分配给对应类型的问题排查

TypeScript泛型工厂函数返回类型推断错误问题解决

问题重现

现有以下TypeScript类型定义:

enum QType {
    One = "one",
    Two = "two",
}

type QFeedback<T extends QType> = T extends QType.One ? {
    key: string;
} : {
    key1: string;
    key2: string;
}

type QContent<T extends QType> = {
    text: string;
    feedback: QFeedback<T>
}

实现工厂函数时,出现feedback属性无法分配给QFeedback<T>类型的错误,错误提示:

Type '{ key: string; } | { key1: string; key2: string; }' is not assignable to type 'QFeedback'.
Type '{ key: string; }' is not assignable to type 'QFeedback'.

工厂函数代码:

function factory<T extends QType>(qType: T): QContent<T> {
    return {
        text: "",
        feedback: qType === QType.One ? {
            key: "",
        }: {
            key1: "",
            key2: "",
        }
    }
}

错误原因

TypeScript编译器无法在泛型函数内部,通过qType === QType.One这个条件判断来细化泛型参数T的具体类型。虽然我们能根据输入的qType确定feedback的类型,但编译器会把feedback推断成{ key: string; } | { key1: string; key2: string; }联合类型,而QFeedback<T>是条件类型——对于特定的T(比如QType.One),它是单一确定的类型,并非联合类型,因此联合类型无法赋值给这个条件类型。

解决方案

方案1:使用函数重载(推荐)

函数重载能为不同的输入参数指定精确的返回类型,既解决类型推断问题,又能给调用方提供更清晰的类型提示:

enum QType {
    One = "one",
    Two = "two",
}

type QFeedback<T extends QType> = T extends QType.One ? {
    key: string;
} : {
    key1: string;
    key2: string;
}

type QContent<T extends QType> = {
    text: string;
    feedback: QFeedback<T>
}

// 重载签名:为每个QType枚举值指定对应的返回类型
function factory(qType: QType.One): QContent<QType.One>;
function factory(qType: QType.Two): QContent<QType.Two>;

// 实现签名:处理通用逻辑
function factory(qType: QType): QContent<QType> {
    return {
        text: "",
        feedback: qType === QType.One ? {
            key: "",
        } : {
            key1: "",
            key2: "",
        } as QFeedback<QType>
    }
}

方案2:类型断言

如果不想使用重载,也可以直接对feedback进行类型断言,告诉编译器它的类型就是QFeedback<T>:

function factory<T extends QType>(qType: T): QContent<T> {
    return {
        text: "",
        feedback: (qType === QType.One ? {
            key: "",
        } : {
            key1: "",
            key2: "",
        }) as QFeedback<T>
    }
}

内容的提问来源于stack exchange,提问作者netiul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:43:17