I have a large object containing various animals with different characteristics. I'm looking to properly type this object in TypeScript.
interface Animal {
legs: 0 | 1 | 2 | 3 | 4;
}
const Animals: Record<string, Animal> = {
snake: { legs: 0 },
dog: { legs: 4 },
bird: { legs: 2},
// many more entries...
};
If I define the object as Record<string, Animal>, all strings are allowed as keys, leading to potential mistakes like Animals.birb
. Restricting the keys manually with something like
Record<"snake" | "dog" | "bird" ... , Animal>
for every key isn't practical due to the size of the object.
Without explicit typing, TypeScript defaults to inferring the type as
{ snake: { legs: number}, dog: { legs: number}, ... }
.
This is problematic because it doesn't capture the essence of an animal being of type Animal
and not just any object with a numeric property legs
,
The ideal type declaration would be
{ snake: Animal, dog: Animal, ... }
Mentioning as Animal
for each entry seems cumbersome.
Is there a more efficient way to precisely type this object?