0
0
Typescriptprogramming~15 mins

Union vs intersection mental model in Typescript - Hands-On Comparison

Choose your learning style9 modes available
Union vs Intersection Mental Model in TypeScript
📖 Scenario: Imagine you are building a simple system to describe different types of pets and their characteristics. You want to understand how to combine types using union and intersection in TypeScript to model pets that can have multiple traits or belong to multiple categories.
🎯 Goal: You will create TypeScript types using union and intersection to represent pets with different features. Then, you will write code to see how these types behave when combined.
📋 What You'll Learn
Create union and intersection types with exact names and values
Use variables with explicit types to demonstrate union and intersection
Write code that shows the difference in allowed values for union and intersection types
Print the results to the console exactly as instructed
💡 Why This Matters
🌍 Real World
Understanding union and intersection types helps when modeling complex data in apps, like user roles or product features that can overlap or be exclusive.
💼 Career
Many programming jobs require working with TypeScript or similar typed languages where combining types correctly is important for safe and clear code.
Progress0 / 4 steps
1
Create basic pet types
Create two TypeScript types called Cat and Dog. Cat should have a property meows set to true. Dog should have a property barks set to true. Use type aliases exactly as type Cat = { meows: true } and type Dog = { barks: true }.
Typescript
Need a hint?

Use type keyword to create type aliases with exact property names and values.

2
Create union and intersection types
Create a union type called PetUnion that is either Cat or Dog. Create an intersection type called PetIntersection that combines Cat and Dog. Use exactly type PetUnion = Cat | Dog and type PetIntersection = Cat & Dog.
Typescript
Need a hint?

Use | for union and & for intersection between types.

3
Create variables with union and intersection types
Create a variable called pet1 of type PetUnion and assign it an object with meows: true. Create a variable called pet2 of type PetIntersection and assign it an object with both meows: true and barks: true. Use exactly const pet1: PetUnion = { meows: true } and const pet2: PetIntersection = { meows: true, barks: true }.
Typescript
Need a hint?

Assign objects matching the union and intersection types exactly.

4
Print the variables to see the difference
Write two console.log statements to print pet1 and pet2. Use exactly console.log(pet1) and console.log(pet2).
Typescript
Need a hint?

Use console.log to print the variables exactly.