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

TypeScript映射类型中`as`关键字的作用及示例转换原因

映射类型中as关键字的解析与作用

为什么你的示例会生成[x: number]: any

先拆解你的代码:

type foo = "a" | "b" | 1 | 2;
type bar = {
    [k in foo as number]: any
}

这里的as number是对遍历到的每个k做类型转换:

  • 当k是"a"或"b"时,字符串类型无法合法转换为number,TypeScript会将其判定为never类型;
  • 当k是1或2时,数字字面量可以安全转换为number类型,结果就是number。

而映射类型会自动忽略never类型的键,最终剩下的有效键类型只有number。TypeScript会把多个重复的数字类型键合并为数字索引签名,也就是你看到的{ [x: number]: any }。

映射类型中as的实际作用

as是TypeScript 4.1引入的**键重映射(Key Remapping)**语法,核心是在遍历联合类型生成映射类型时,对每个键进行自定义处理,主要用途包括:

1. 过滤不需要的键

通过将目标键转换为never,可以在最终类型中剔除这些键:

type foo = "a" | "b" | 1 | 2;
type StringKeysOnly = {
  [k in foo as k extends string ? k : never]: any
};
// 最终类型:{ a: any; b: any }

2. 重命名键

可以通过模板字符串或类型转换修改键的名称/类型:

type foo = "name" | "age";
type PrefixedKeys = {
  [k in foo as `user_${k}`]: string
};
// 最终类型:{ user_name: string; user_age: string }

3. 转换键的类型

将键的类型转换为兼容的其他类型,比如把数字字面量键转为字符串类型:

type foo = 1 | 2 | 3;
type StringifiedKeys = {
  [k in foo as `${k}`]: number
};
// 最终类型:{ "1": number; "2": number; "3": number }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:40:19