小编Tot*_*one的帖子

Typescript:无法在映射类型上声明其他属性

我在使用 TypeScript 输入对象时遇到问题

我声明了应用程序的某些文件使用的类型:

type Category = "cat1"|"cat2"|"cat3"|"cat4"
Run Code Online (Sandbox Code Playgroud)

我用来Category输入一个对象并且一切正常使用:

const obj: {
  [key in Category]: string
} = {---}
Run Code Online (Sandbox Code Playgroud)

但现在,我想添加 2 个不是Category对象值的键。我认为通过输入这样的对象会很容易:

const obj: {
  customKey1: string
  customKey2: string
  [key in Category]: string
} = {---}
Run Code Online (Sandbox Code Playgroud)

但 TS 没有按预期工作,而是发送了 3 个错误:TS2464、TS1170 和 TS2693

A computed property name must be of type 'string', 'number', 'symbol' or 'any'. ts(2464)
'Category' only refers to a type, but is using as a value here. ts(2693)
A computed property name in …
Run Code Online (Sandbox Code Playgroud)

typescript

10
推荐指数
1
解决办法
2820
查看次数

标签 统计

typescript ×1