Created
June 14, 2022 01:13
-
-
Save UltiRequiem/28e617b5c754547bea8da928650a8be7 to your computer and use it in GitHub Desktop.
TypeScript Array Type Guards explicados en dos minutos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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