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

TypeScript中的number究竟是什么?类型、常量还是关键字?

问题解答

在这个TypeScript场景里,typeof animals[number]中的number是TypeScript类型系统里的特殊语法关键字,既不是普通的number类型,也不是常量。

具体作用

它的作用是在类型查询中,代表数组的所有有效数值索引。当你对一个用as const断言为只读常量的数组使用[number]索引时,TypeScript会自动收集该数组所有数值键对应的值的类型,将它们合并成一个联合类型。

示例代码

const animals = ['dog', 'cat', 'hen'] as const
type Animal = typeof animals[number] // type Animal = "dog" | "cat" | "hen"

这里的number本质是TypeScript为数组类型查询提供的语法糖,专门用来快速获取数组元素的类型联合,而不是指代某个具体的数值或普通的number类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:12:02