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 through the type system so that I won't forget to update the lookup if the enum expands. I tried this:
type EnumDictionary<T, U> = {
[K in keyof T]: U;
};
enum Direction {
Up,
Down,
}
const lookup: EnumDictionary<Direction, number> = {
[Direction.Up]: 1,
[Direction.Down]: -1,
};
But I'm getting this weird error:
Type '{ [Direction.Up]: number; [Direction.Down]: number; }' is not assignable to type 'Direction'.
Which seems weird to me because it's saying that the type of lookup
should be Direction
instead of EnumDictionary<Direction, number>
. I can confirm this by changing the lookup
declaration to:
const lookup: EnumDictionary<Direction, number> = Direction.Up;
and there are no errors.
How can I create a lookup type for an enum that guarantees every value of the enum will lead to another value of a different type?
TypeScript version: 3.2.1