#typescript
#types
#advanced
Day 13: Union and Intersection Types
Combining Types
Welcome to Day 13! Phase 3 is all about the “Type” in TypeScript. Today we look at how to mix and match them.
Union Types (|)
A union type describes a value that can be one of several types. It uses the vertical bar |.
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
printId(101); // OK
printId("202"); // OK
// printId({ key: 1 }); // Error
Narrowing: When working with a union, TS only lets you access members common to all types in the union. To use type-specific members, you must “narrow” the type (check what it is).
function printId(id: number | string) {
if (typeof id === "string") {
console.log(id.toUpperCase()); // allowed
} else {
console.log(id); // inferred as number
}
}
Intersection Types (&)
An intersection type combines multiple types into one. The new type has all the features of the combined types.
interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface ArtworksData {
artworks: { title: string }[];
}
type ArtworksResponse = ArtworksData & ErrorHandling;
const handleArtistsResponse = (response: ArtworksResponse) => {
if (response.error) {
console.error(response.error.message);
return;
}
console.log(response.artworks);
};
Intersections are perfect for “Mixins” or when adding properties to an existing object type.
Challenge for Today
- Create a type
Carwithdrive(). - Create a type
Planewithfly(). - Create a type
FlyingCarthat is an intersection of both. - Implement an object of type
FlyingCarand call both methods.
See you on Day 14 for Literal Types and Enums!