Let's say you have an enum Animal and a string value and you want to check if the value is an animal.
enum Animal {
Cat = "cat",
Dog = "dog",
}
const someInputValue = "cat";
// TS compiler will show an error,
// because "cat" is not assignable to Animal.
// We need to check if `someInputValue` is an animal.
someFunctionThatExpectsAnAnimal(someInputValue);TypeScript supports type guards and type predicates that lets you do this. The function isAnimal accepts a string value and returns a boolean whether the value is a valid animal or not.
function isAnimal(value: string): value is Animal {
return Object.values<string>(Animal).includes(value);
}If the function returns true, TypeScript knows that the value is an Animal and infers that type inside the if statement. You don't need to write as Animal.
if (isAnimal(someInputValue)) {
// TypeScript knows that `someInputValue` is of type `Animal`
someFunctionThatExpectsAnAnimal(someInputValue);
}