You need to enable JavaScript to run this app. TypeScript中如何用自定义类型约束const对象键并保留字面量类型
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何用自定义类型约束const对象键并保留字面量类型

问题本质

你为ABSentences添加的前置显式类型注解优先级高于as const的字面量窄化逻辑,导致值的类型被拓宽为string,丢失了具体的字面量信息,同时前置注解也不会和as const的结果做合并推导。


方案1:使用TS 4.9+ 支持的satisfies操作符(推荐)

satisfies的作用是在不覆盖原有类型推导的前提下,校验值是否符合目标类型约束,完美适配你的需求:

type AB = {
    A?: any
    B?: any
}

// 去掉前置类型注解,用satisfies做后置校验
const ABSentences = {
    A: 'this is A.',
    B: 'this is B.',
} as const satisfies Record<keyof Required<AB>, string>;

此时ABSentences的类型就是你预期的字面量类型:

const ABSentences: {
    readonly A: 'this is A.';
    readonly B: 'this is B.';
}

如果你后续给AB新增属性C,TS会立即抛出错误,提示ABSentences缺少必填属性C。


方案2:兼容低版本TS的泛型工具函数

如果你的TS版本低于4.9,无法使用satisfies,可以通过一个无运行时开销的泛型工具函数实现相同效果:

type AB = {
    A?: any
    B?: any
}

// 定义泛型约束工具函数,不会产生任何实际运行时代码
const defineABSentences = <T extends Record<keyof Required<AB>, string>>(obj: T) => obj;

const ABSentences = defineABSentences({
    A: 'this is A.',
    B: 'this is B.',
} as const);

如果你用的是TS 5+,还可以使用const类型参数,省略手动写as const:

const defineABSentences = <const T extends Record<keyof Required<AB>, string>>(obj: T) => obj;

// 不需要加as const,自动推导字面量类型
const ABSentences = defineABSentences({
    A: 'this is A.',
    B: 'this is B.',
});

内容的提问来源于stack exchange,提问作者足立蓮

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 03:15:02