TypeScript version: 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. 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.
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)
'}' 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)
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.
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.
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"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.