0
0
Typescriptprogramming~15 mins

Type alias for unions in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Type alias for unions
📖 Scenario: You are building a simple program to categorize different types of pets by their names and types.
🎯 Goal: Create a type alias for a union of pet types, use it in a variable, and print the pet's type.
📋 What You'll Learn
Create a type alias called PetType that is a union of the strings 'dog', 'cat', and 'bird'.
Create a variable called myPet with the type PetType and assign it the value 'cat'.
Print the value of myPet.
💡 Why This Matters
🌍 Real World
Type aliases for unions help you restrict variables to specific allowed values, making your code safer and easier to understand.
💼 Career
Many jobs require writing clear and safe TypeScript code, especially when working with APIs or user input where only certain values are valid.
Progress0 / 4 steps
1
Create a type alias for pet types
Create a type alias called PetType that is a union of the strings 'dog', 'cat', and 'bird'.
Typescript
Need a hint?

Use the type keyword followed by the alias name, then assign the union of string literals separated by |.

2
Create a variable with the type alias
Create a variable called myPet with the type PetType and assign it the value 'cat'.
Typescript
Need a hint?

Declare myPet with let, specify the type PetType, and assign the string 'cat'.

3
Use the variable in a function
Create a function called describePet that takes a parameter pet of type PetType and returns a string describing the pet type. Then call describePet with myPet and store the result in a variable called description.
Typescript
Need a hint?

Define a function with parameter pet of type PetType that returns a string using a template literal.

4
Print the description
Print the value of the variable description using console.log.
Typescript
Need a hint?

Use console.log(description) to print the description.