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

如何在映射类型中将字符串字面量联合类型转为内联形式?

可行,有两种常用方法可以实现:

方法一:使用条件类型强制展开别名

通过infer关键字让TypeScript展开类型别名,替换原有的类型定义:

type UnionType = 'cat' | 'dog' | 'bird';
type MappedType = {
  [Key in UnionType]: UnionType extends infer U ? U : never;
};

此时查看MappedType的类型,就会显示为:

type MappedType = {
    'cat': 'cat' | 'dog' | 'bird';
    'dog': 'cat' | 'dog' | 'bird';
    'bird': 'cat' | 'dog' | 'bird';
}

方法二:基于常量数组推导类型(适合需要维护单一数据源的场景)

如果不想先定义类型别名,而是从常量数组推导联合类型,也能直接得到展开后的结果:

const animals = ['cat', 'dog', 'bird'] as const;
type UnionType = typeof animals[number];
type MappedType = {
  [Key in UnionType]: UnionType;
};

这种方式下,MappedType的属性值同样会显示为具体的联合值而非类型别名。

本质上,TypeScript会优先显示用户定义的类型别名,通过上述技巧可以绕过这个默认行为,让类型显示为展开后的具体联合成员。

内容的提问来源于stack exchange,提问作者NeoZoom.lua

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 02:32:32