0
0
Typescriptprogramming~30 mins

Excess property checking behavior in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Excess Property Checking Behavior
📖 Scenario: Imagine you are creating a simple app to manage user profiles. Each user profile should have a name and age. Sometimes, extra information might be added by mistake. TypeScript helps catch these mistakes with excess property checking.
🎯 Goal: You will create a user profile object, add a configuration variable, use a function to accept only allowed properties, and finally print the user profile to see how TypeScript handles extra properties.
📋 What You'll Learn
Create an interface UserProfile with name as string and age as number
Create a variable user with name, age, and an extra property location
Create a boolean variable allowExtra set to false
Write a function createUser that accepts only UserProfile type
Call createUser with user and print the result
💡 Why This Matters
🌍 Real World
In real apps, you often receive data with extra fields. Understanding excess property checking helps you catch mistakes early and keep your data clean.
💼 Career
Many jobs require writing safe TypeScript code. Knowing how to handle excess properties is important for building reliable applications and avoiding bugs.
Progress0 / 4 steps
1
Create the UserProfile interface and user object
Create an interface called UserProfile with properties name (string) and age (number). Then create a variable called user with name set to "Alice", age set to 30, and an extra property location set to "Wonderland".
Typescript
Need a hint?

Use interface UserProfile { name: string; age: number; } and then create const user = { name: "Alice", age: 30, location: "Wonderland" }.

2
Add a configuration variable
Create a boolean variable called allowExtra and set it to false.
Typescript
Need a hint?

Just write const allowExtra = false; below the user object.

3
Write a function to accept only UserProfile type
Write a function called createUser that takes one parameter profile of type UserProfile and returns it.
Typescript
Need a hint?

Define function createUser(profile: UserProfile): UserProfile { return profile; }.

4
Call createUser and print the result
Call the function createUser with the variable user and print the result using console.log.
Typescript
Need a hint?

Write console.log(createUser(user)); to see the output.