I have a function that takes an array of Animals, and returns a map where the keys are the animals and the values are their fur colors:
export enum Animals {
CAT = 'CAT',
DOG = 'DOG',
SEAL_PUP = 'SEAL_PUP',
}
const furColors = ['BROWN', 'BLACK', 'WHITE'];
function getFurColor(animals: Animals[]): Partial<Record<Animals, string>> {
// call some internal service to get fur colors for each Animal, then return them as a Record. Here as example we randomly assign:
return animals.reduce((acc, animal) => {
acc[animal] = furColors[Math.floor(Math.random() * furColors.length)];
return acc;
}, {});
}
I want to specify the return type of this function in a way that when I make the following function call:
getFurColor([Animals.CAT, Animals.DOG]);
typescript indicates that the return type of this function is
{ ['CAT']: string, ['DOG']: string };
and if I attempt to access ['SEAL_PUP']
from the output, it will generate an error message
TS2339: property 'SEAL_PUP' does not exist on type { ['CAT']: string, ['DOG']: string }
.