[英]Can't have a regular property and computed property keys in the same interface
TypeScript 版本:3.6.4
在我的 state 中,我想在接口內同時擁有計算屬性和常規屬性鍵,但 TypeScript 無法解析它。 在存儲庫上創建 GitHub 問題之前,我只是想確保我沒有做錯什么並浪費開發人員的時間。
type Stat = 'hp' | 'attack' | 'defense' | 'speed';
interface State {
[x in Stat]: number;
type: string
}
我認為這會起作用,但隨后 TypeScript 突出顯示type
並說'}' expected. ts(1005)
'}' expected. ts(1005)
。 如果我將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)
。 如果我注釋掉這兩行之一,TypeScript 完全可以接受。
我在這里做錯了什么還是這不可能?
如果沒有更好地了解您的工作,我的建議可能會偏離目標。
您可能可以從映射類型和交集中計算出一些東西:
/** 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; };
這是一個Typescript Playground供您進一步試驗這種方法。
這是你想要的嗎?
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.