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

如何提取TypeScript对象的精确字面量类型?

如何提取对象的精确字面量类型

现有如下对象:

const translations = {
  say_hello: 'hello {{name}}',
};

希望提取该对象的精确类型,即:

type Translations = {
  say_hello: 'hello {{name}}',
}

尝试了自定义类型工具:

type GetExactType<T> = {[K in keyof T]-?: T[K]};

但GetExactType<typeof translations>解析结果是:

{
   say_hello: string,
}

请问有什么解决思路?


解决方法

1. 用as const断言强制推导字面量类型

定义对象时添加as const,让TypeScript把属性值推导为具体的字面量类型,而非宽泛的string:

const translations = {
  say_hello: 'hello {{name}}',
} as const;

type Translations = typeof translations;
// 此时Translations的类型就是 { say_hello: 'hello {{name}}' }

2. 基于类型推断提取字面量(无法修改原对象时)

如果不能修改原对象的定义,可以通过infer结合模板字面量匹配,提取精确的字面量类型(仅适用于已知属性格式的场景):

type ExtractLiteral<T extends { say_hello: string }> = 
  T extends { say_hello: infer U extends `hello {{${string}}}` } 
    ? { say_hello: U } 
    : never;

type Translations = ExtractLiteral<typeof translations>;
// 结果为 { say_hello: 'hello {{name}}' }

3. 使用satisfies关键字(TypeScript 4.9及以上)

如果想保留对象属性的可变性,同时让TS推导字面量类型,可以用satisfies约束对象结构:

type TranslationShape = {
  say_hello: string;
};

const translations = {
  say_hello: 'hello {{name}}',
} satisfies TranslationShape;

type Translations = typeof translations;
// 类型为 { say_hello: 'hello {{name}}' }

内容的提问来源于stack exchange,提问作者c.bear

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:05:30