Skip to content

Instantly share code, notes, and snippets.

@UltiRequiem
Created June 14, 2022 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UltiRequiem/28e617b5c754547bea8da928650a8be7 to your computer and use it in GitHub Desktop.
Save UltiRequiem/28e617b5c754547bea8da928650a8be7 to your computer and use it in GitHub Desktop.
TypeScript Array Type Guards explicados en dos minutos
interface Pizza {
type: "pizza";
slices: number;
}
interface Hamburger {
type: "hamburger";
vegetarian: boolean;
}
type Food = Hamburger | Pizza;
const foods: Food[] = getFoods();
function getFoods(): Food[] {
throw new Error("Function not implemented.");
}
const hamburger = foods.find(
(food): food is Hamburger => food.type === "hamburger"
);
const isVegetarian = hamburger?.vegetarian;
const isPizza = (food: Food): food is Pizza => food.type === "pizza";
const slices = foods.filter(isPizza).map((pizza) => pizza.slices);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment