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

如何让TypeScript自动推断第一种函数写法的返回类型

让TypeScript自动推断对象映射函数的具体返回类型

你遇到的问题是因为TypeScript默认会将对象字面量的字符串属性值拓宽为string类型,而条件分支写法能保留字面量类型。要让第一种写法自动推断出具体的联合类型,有两种简单的方法:

方法1:给对象字面量添加as const断言

通过as const强制TypeScript保留对象属性的字面量类型,不进行类型拓宽:

type Status = "pending_validation" | "ready_for_payment" | "paid";

function colorStatus2(status: Status) {
    return {
        pending_validation: 'warning',
        ready_for_payment: 'inactive',
        paid: 'active',
    } as const[status];
}

此时colorStatus2的返回类型会被自动推断为'warning' | 'inactive' | 'active'。

方法2:提前定义带as const的映射常量

如果映射逻辑需要复用,先定义一个只读的常量对象,再在函数中引用它:

type Status = "pending_validation" | "ready_for_payment" | "paid";

const statusColorMap = {
    pending_validation: 'warning',
    ready_for_payment: 'inactive',
    paid: 'active',
} as const;

function colorStatus2(status: Status) {
    return statusColorMap[status];
}

这种方式更清晰,同时也能让TypeScript准确推断出返回的字面量联合类型。

原理说明

as const会将对象转换为只读的字面量类型,阻止TypeScript把字符串属性值自动拓宽为string。这样当你用Status类型的索引访问对象时,TypeScript就能推导出所有可能的属性值组成的联合类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:41:12