Is there any way to tell Typescript that I have an array that will be indexed by a given numeric enum? For example I might have this code:
enum Animals {
dog,
bear,
cat,
}
const animalColours: string[] = [
"black",
"brown",
"white",
];
But if I add an extra animal type I can easily forget to update animalColours
, which leads to a runtime error. An improvement is to use Record
:
enum Animals {
dog,
bear,
cat,
}
const animalColours: Record<Animals, string> = {
[Animals.dog]: "black",
[Animals.bear]: "brown",
[Animals.cat]: "white",
};
Typescript will then detect if I miss any variants. However I do not want to use a Record
for various reasons that I won't go into here. Is there any way to achieve the same thing with an array? The best I can come up with is to convert the Record
at runtime, but that sucks because it has a runtime cost, especially because you have to sort them (iteration order isn't guaranteed).
const animalColoursRecord: Record<Animals, string> = {
[Animals.dog]: "black",
[Animals.bear]: "brown",
[Animals.cat]: "white",
};
// In fact this doesn't even work because Object.entries() always returns
// [string; string][].
const animalColours: string[] = Object.entries(animalColoursRecord).sort((a, b) => a[0] > b[0]).map(x => x[1])
It also means Typescript won't complain about animalColours[10]
.
Is there a way to get the type safety of Record<T, U>
but using arrays?