[英]Can't have a regular property and computed property keys in the same interface
TypeScript version: 3.6.4 TypeScript 版本:3.6.4
In my state, I want to have both a computed property and a regular property key inside an interface but TypeScript is having trouble parsing that.在我的 state 中,我想在接口内同时拥有计算属性和常规属性键,但 TypeScript 无法解析它。 Before creating a GitHub issue on the repository, I just want to make sure I'm not doing something wrong and wasting the devs' time.
在存储库上创建 GitHub 问题之前,我只是想确保我没有做错什么并浪费开发人员的时间。
type Stat = 'hp' | 'attack' | 'defense' | 'speed';
interface State {
[x in Stat]: number;
type: string
}
I thought that would work but then TypeScript highlights type
and says '}' expected. ts(1005)
我认为这会起作用,但随后 TypeScript 突出显示
type
并说'}' expected. ts(1005)
'}' expected. ts(1005)
. '}' expected. ts(1005)
。 If I put type
at the top, it highlights [x in Stat]
and says A computed property name must be of type 'string', 'number', 'symbol', or 'any'. ts(2464)
如果我将
type
放在顶部,它会突出显示[x in Stat]
并说A computed property name must be of type 'string', 'number', 'symbol', or 'any'. ts(2464)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'. ts(2464)
& 'Stat' only refers to a type, but is being used as a value here.ts(2693)
. A computed property name must be of type 'string', 'number', 'symbol', or 'any'. ts(2464)
& 'Stat' only refers to a type, but is being used as a value here.ts(2693)
。 If i comment out one of the 2 lines, TypeScript is totally okay with it.如果我注释掉这两行之一,TypeScript 完全可以接受。
Am I doing something wrong here or is this just not possible?我在这里做错了什么还是这不可能?
Without a better understanding of what you are working on, my proposal may be off target.如果没有更好地了解您的工作,我的建议可能会偏离目标。
You can probably work out something from mapped types and intersection:您可能可以从映射类型和交集中计算出一些东西:
/** Refefernce interface */
interface IStat {
attack: unknown;
defense: unknown;
hp: unknown;
speed: unknown;
}
/** (optional) `keyof` reference interface */
type Stat = keyof IStat
/** Mapped IStat properties intersected with `type` */
type State = {
[K in keyof IStat]?: number; // change `number` with IStat[K] if you want the types from IStat;
} & { type: string; };
Here is a Typescript Playground for you to experiment further this approach.这是一个Typescript Playground供您进一步试验这种方法。
is this what you want?这是你想要的吗?
type Stat = 'hp' | 'attack' | 'defense' | 'speed';
type State = Record <Stat, number> & {
type: string;
}
const s: State = {
hp: 100,
attack: 12,
defense: 12,
speed: 3,
type: "myType"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.