I have a store which keys a few different types by their IDs
interface Dog { type: "dog"; woofs: string; }
interface Cat { type: "cat"; meows: string; }
type Pet = Dog | Cat;
type AnimalState = Record<string, Pet>
And I would like a function that returns a pet specific type, by it's key/ID.
function getSpecificAnimal(state: AnimalState, key: string, type: Pet["type"]) {
const pet = state[key];
if (pet.type === type) {
return pet;
}
throw new Error("pet was wrong type");
}
const aDog = getSpecificAnimal(state, "a", "dog"); // should return type Dog, or throw an exception
But I cannot figure out how to get Typescript to narrow down the return of the getSpecificAnimal function.
I tried using generics and a type map to relate all the arguments, but Typescript still was not satisfied
type PetTypeMap = {
dog: Dog,
cat: Cat,
}
function getAnimalOfType<T extends Pet, K extends T["type"]>(animals: AnimalState, id: string, type: K): PetTypeMap[K] {
const pet = animals[id];
// ^?
if (pet.type === type) {
return pet;
}
throw new Error("wrong pet type");
}
I've tried a bunch of other ways and just cannot get this to work. Is this type of narrowing not possible with Typescript?