I have two enums imported from a different files
export enum Id {
X = 'AA',
Y = 'BB',
Z = 'CC'
}
export enum Place {
us = 'USA',
ind = 'INDIA',
}
I want to create a dictionary something like:
const valueThreshold = {
Id.X : {
Place.us : {
'foo' : 1,
}
Place.ind : {
'foo' : 1,
}
},
Id.Y : {
Place.us : {
'foo' : 6,
}
Place.ind : {
'foo' : 4,
}
}
}
which I can then query like
valueThreshold[Id.X][Place.us]['foo']
.
Note my query would be something like valueThreshold['AA']['USA']['foo']
when executed.
I tried creating using Record
(see below) however I can't seem to use the enum value as key. I get an error error Extra space after computed key 'Id.X'
which means the key was taken as 'Id.X'. I want the key to be 'AA'
import { Id, Place } from './config';
const valueThreshold: Record<string, Record<string, Record<string, number>>> = {
[Id.x] : {
[Place.us] : {
'foo' : 5
},
[Place.ind] : {
'foo' : 1
}
}
}
Any pointers on how to do this correctly would be really really helpful.
CodePudding user response:
Computed property names is the correct way. You should delete the space after the computed key:
enum Id {
X = 'AA',
Y = 'BB',
Z = 'CC'
}
enum Place {
us = 'USA',
ind = 'INDIA',
}
const valueThreshold = {
[Id.X]: {
[Place.us]: {
'foo': 1,
},
[Place.ind]: {
'foo': 1,
}
},
[Id.Y]: {
[Place.us]: {
'foo': 6,
},
[Place.ind]: {
'foo': 4,
}
}
}
console.log(valueThreshold[Id.X][Place.us]['foo'])
// Use enum as the key of a Record
const valueThreshold2: Record<Id, Record<Place, Record<string, number>>> = {
[Id.X]: {
[Place.us]: {
'foo': 5
},
[Place.ind]: {
'foo': 1
}
},
[Id.Y]: {
[Place.us]: {
'foo': 6,
},
[Place.ind]: {
'foo': 4,
}
},
[Id.Z]: {
[Place.us]: {
'foo': 2,
},
[Place.ind]: {
'foo': 3,
}
}
}