0
0
Typescriptprogramming~30 mins

Why advanced types are needed in Typescript - See It in Action

Choose your learning style9 modes available
Why advanced types are needed
📖 Scenario: Imagine you are building a simple app that tracks different types of pets and their unique details. You want to make sure your program handles each pet type correctly and safely.
🎯 Goal: You will create a basic data structure for pets, add a type to distinguish pet kinds, write code that uses advanced types to handle different pet details safely, and finally display the pet information.
📋 What You'll Learn
Create a list of pets with exact properties
Add a type property to each pet to identify its kind
Use a TypeScript union type to define pet types
Use a type guard with switch to handle each pet kind
Print the pet details with correct type safety
💡 Why This Matters
🌍 Real World
In real apps, you often have data that can be different types but share some common parts. Advanced types help you write code that works correctly for each kind.
💼 Career
Understanding advanced types is important for writing safe, maintainable TypeScript code in professional software development.
Progress0 / 4 steps
1
Create the initial pet list
Create a variable called pets as an array with these exact objects: { name: 'Buddy', age: 3, type: 'dog' }, { name: 'Mittens', age: 2, type: 'cat' }, and { name: 'Goldie', age: 1, type: 'fish' }.
Typescript
Need a hint?

Use const pets = [ ... ] with the exact objects inside.

2
Define the Pet type using union types
Create a TypeScript type called Pet as a union of three object types: { name: string; age: number; type: 'dog'; barkVolume: number; }, { name: string; age: number; type: 'cat'; livesLeft: number; }, and { name: string; age: number; type: 'fish'; waterType: string; }.
Typescript
Need a hint?

Use the type keyword and union | to combine the three pet object types.

3
Add pet details using the Pet type
Create a new variable called detailedPets as an array of Pet objects. Add the same pets as before but include these extra properties: for the dog add barkVolume: 5, for the cat add livesLeft: 9, and for the fish add waterType: 'freshwater'.
Typescript
Need a hint?

Use const detailedPets: Pet[] = [ ... ] with the exact objects including the extra properties.

4
Print pet details using a type guard
Use a for loop with variable pet to go through detailedPets. Inside the loop, use a switch on pet.type to print these exact lines: for 'dog' print "Dog: Buddy barks at volume 5", for 'cat' print "Cat: Mittens has 9 lives left", and for 'fish' print "Fish: Goldie lives in freshwater water".
Typescript
Need a hint?

Use a for loop and a switch on pet.type. Print the exact lines with console.log.