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

TypeScript如何为带const断言的对象同时实现值类型校验和键联合类型提取

显式给变量标注Record<string, ISiteDetails>类型会触发类型拓宽,丢失初始化时的精确键信息,可通过以下两种方案同时满足值校验和保留精确键类型的需求:

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

satisfies 是TypeScript 4.9版本引入的语法,特性是仅校验值是否符合目标类型,不会拓宽变量的原始类型,完美适配该场景:

interface ISiteDetails {
    url: string;
}
const sites = {
    stackoverflow: {url: 'https://stackoverflow.com/'},
    google: {url: 'https://www.google.com/'},
    azure: {url: 'https://portal.azure.com/'}
} as const satisfies Record<string, ISiteDetails>;

// 可正常提取精确键联合类型
type SiteNames = keyof typeof sites; 
// 类型为 "stackoverflow" | "google" | "azure"
// 同时值的类型校验完全生效,若属性不符合ISiteDetails定义会直接抛出类型错误

方案2:低版本TS 通用工具函数方案

如果项目TypeScript版本低于4.9,可通过泛型工具函数实现相同效果:

interface ISiteDetails {
    url: string;
}

// 泛型工具函数:约束值类型的同时保留输入对象的精确类型
const defineSites = <T extends Record<string, ISiteDetails>>(sites: T) => sites as const;

const sites = defineSites({
    stackoverflow: {url: 'https://stackoverflow.com/'},
    google: {url: 'https://www.google.com/'},
    azure: {url: 'https://portal.azure.com/'}
});

type SiteNames = keyof typeof sites;
// 同样得到精确的键联合类型 "stackoverflow" | "google" | "azure"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:06:09