为什么TypeScript的interface中不能使用in关键字定义索引签名
问题解答
你遇到的报错本质是TypeScript 语法限制:[key in 联合类型]是映射类型的专属语法,仅支持在type类型别名中使用,无法在interface接口定义中使用。
- 你最早写的
[key: string]: string是普通索引签名语法,接口和类型别名都支持,作用是声明「所有该类型的键都对应指定值类型」,支持任意符合类型的动态键,所以两种写法都能正常运行。 [key in Keys]: string不属于普通索引签名,是映射类型语法,作用是遍历联合类型Keys的每一个成员,将每个成员都生成为对象的固定键,属于生成固定键集合类型的语法糖,TypeScript 明确规定该语法仅可用于type类型别名定义。
当你在接口中写[key in Keys]时,TS 无法识别为映射类型语法,会将其解析为普通的计算属性,而计算属性要求传入运行时真实存在的值,但Keys只是 TypeScript 类型,编译后会被擦除不存在于运行时,因此触发对应报错:
A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1169)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
'Keys' only refers to a type, but is being used as a value here.ts(2693)
如果想在接口中实现相同的固定键约束,可以通过继承内置映射类型Record实现,效果和你写的InputData2完全一致:
type Keys = "username" | "password" | "confirm" | "captcha"; export interface InputData extends Record<Keys, string> {}
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

