0
0
Typescriptprogramming~15 mins

How intersection combines types in Typescript - Try It Yourself

Choose your learning style9 modes available
How intersection combines types
📖 Scenario: Imagine you are creating a profile system where a user can be both a Student and an Employee. You want to combine these two roles into one type that has all properties from both.
🎯 Goal: You will create two types, then combine them using an intersection type. Finally, you will create a variable of the combined type and print its properties.
📋 What You'll Learn
Create a type called Student with properties name (string) and grade (number).
Create a type called Employee with properties name (string) and salary (number).
Create an intersection type called StudentEmployee that combines Student and Employee.
Create a variable called person of type StudentEmployee with all required properties.
Print the name, grade, and salary of person.
💡 Why This Matters
🌍 Real World
Combining multiple roles or features into one object is common in user profiles, permissions, and settings in real applications.
💼 Career
Understanding intersection types helps you write flexible and safe TypeScript code, which is valuable for frontend and backend development jobs.
Progress0 / 4 steps
1
Create the Student and Employee types
Create a type called Student with properties name (string) and grade (number). Then create a type called Employee with properties name (string) and salary (number).
Typescript
Need a hint?

Use type keyword to create types. Properties are written as propertyName: type;.

2
Create the intersection type StudentEmployee
Create an intersection type called StudentEmployee that combines the types Student and Employee using the & operator.
Typescript
Need a hint?

Use type StudentEmployee = Student & Employee; to combine both types.

3
Create a variable of type StudentEmployee
Create a variable called person of type StudentEmployee and assign it an object with name as "Alice", grade as 90, and salary as 30000.
Typescript
Need a hint?

Make sure the object has all properties from both types.

4
Print the properties of person
Write a console.log statement to print the name, grade, and salary properties of the person variable.
Typescript
Need a hint?

Use a template string inside console.log to show all properties.