0
0
Typescriptprogramming~20 mins

What structural typing means in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
What structural typing means
📖 Scenario: Imagine you are building a simple system where you want to check if different objects can be used in the same way based on their shape, not their exact type name.
🎯 Goal: You will create objects and functions to see how TypeScript uses structural typing to allow objects with the same shape to be used interchangeably.
📋 What You'll Learn
Create an interface called Person with properties name (string) and age (number).
Create an object called user that matches the Person interface exactly.
Create another object called employee that has the same properties as Person plus an extra property salary (number).
Write a function called greet that takes a parameter of type Person and returns a greeting string using the name property.
Call greet with both user and employee and print the results.
💡 Why This Matters
🌍 Real World
Structural typing helps when working with data from different sources that share common properties, like user profiles or API responses.
💼 Career
Understanding structural typing is key for TypeScript developers to write flexible and type-safe code that integrates well with various libraries and data shapes.
Progress0 / 4 steps
1
Create the Person interface and user object
Create an interface called Person with properties name (string) and age (number). Then create an object called user with name set to "Alice" and age set to 30.
Typescript
Need a hint?

Use interface to define the shape. Then create user with the exact properties.

2
Create the employee object with extra property
Create an object called employee with properties name set to "Bob", age set to 40, and an extra property salary set to 50000. Do not declare employee as type Person explicitly.
Typescript
Need a hint?

Create employee as a plain object with the extra salary property.

3
Write the greet function using Person
Write a function called greet that takes one parameter called person of type Person and returns a string greeting like "Hello, Alice!" using the name property.
Typescript
Need a hint?

Use a template string to include the name in the greeting.

4
Call greet with user and employee and print results
Call the function greet with the user object and print the result. Then call greet with the employee object and print the result.
Typescript
Need a hint?

Use console.log to print the greetings for both objects.