I\'m trying to create a guaranteed lookup for a given enum. As in, there should be exactly one value in the lookup for every key of the enum. I want to guarantee this throug
You can do it as follows:
type EnumDictionary<T extends string | symbol | number, U> = {
[K in T]: U;
};
enum Direction {
Up,
Down,
}
const a: EnumDictionary<Direction, number> = {
[Direction.Up]: 1,
[Direction.Down]: -1
};
I found it surprising until I realised that enums can be thought of as a specialised union type.
The other change is that enum types themselves effectively become a union of each enum member. While we haven’t discussed union types yet, all that you need to know is that with union enums, the type system is able to leverage the fact that it knows the exact set of values that exist in the enum itself.
The EnumDictionary
defined this way is basically the built in Record type:
type Record<K extends string, T> = {
[P in K]: T;
}
enum FunStuff {
PARTY = "party",
CAKE = "cake",
PIZZA = "pizza",
}
So then if you want all of your Enum values to be required
type MapOfFunStuff = {
counts: { [key in FunStuff] : number };
}
Then if you only want values in your enum but any amount of them you can add ?
type MapOfFunStuff = {
counts: { [key in FunStuff]? : number };
}