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

无需const断言将类型收窄为值的穷尽类型联合

问题

我有一段代码,当不对数组subject使用const断言时,推导出来的Subject类型是宽泛的{ field: string },无法精确到数组元素中field的具体值:

/**
 * 未使用const assertion
 */
const subject = [
    {
        "field": "string_1",
    },
    {
        "field": "string_2",
    },
];

type Subject = typeof subject[number];

推导结果:

type Subject = {
    field: string;
}

我需要把Subject类型收窄为包含所有field具体值的联合类型——当给数组添加as const断言后,就能得到预期的精确类型:

/**
 * 使用const assertion
 */
const subject = [
    {
        "field": "string_1",
    },
    {
        "field": "string_2",
    },
] as const;

type Subject = typeof subject[number];

推导结果:

type Subject = {
    readonly field: "string_1";
} | {
    readonly field: "string_2";
}

但我的实际场景中,subject是从第三方库导入的,无法直接对它添加as const断言,请问该如何实现上述的类型收窄效果?

尝试方案

我尝试了以下代码,想通过提取字段来生成精确类型:

/**
 * 未使用const assertion
 */
const subject = [
    {
        "field": "string_1",
    },
    {
        "field": "string_2",
    },
];

/**
 * 错误:A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.
 */
const subjectConst = subject[number]["field"] as const;

type SubjectConst = typeof subjectConst;

但运行时报错:

Error: A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.(1355)


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:03:13