0
0
Typescriptprogramming~15 mins

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

Choose your learning style9 modes available
Why mapped types are needed
📖 Scenario: Imagine you have a list of user settings in a web app. Each setting can be turned on or off. You want to create a new version of these settings where all options are optional, so users can change only what they want.
🎯 Goal: Learn how to use mapped types in TypeScript to create a new type where all properties of an existing type become optional.
📋 What You'll Learn
Create a type called UserSettings with exact properties: theme, notifications, and autoSave all of type boolean
Create a mapped type called OptionalSettings that makes all properties of UserSettings optional
Create a variable called mySettings of type OptionalSettings with only theme set to true
Print the mySettings variable
💡 Why This Matters
🌍 Real World
Mapped types help when you want to create new versions of existing data shapes, like making settings optional or readonly, without rewriting all properties.
💼 Career
Understanding mapped types is important for TypeScript developers to write flexible and reusable code, especially in large projects with complex data models.
Progress0 / 4 steps
1
Create the initial type for user settings
Create a type called UserSettings with these exact properties: theme, notifications, and autoSave, all of type boolean.
Typescript
Need a hint?

Use type UserSettings = { ... } and list the properties with their types.

2
Create a mapped type to make all properties optional
Create a mapped type called OptionalSettings that makes all properties of UserSettings optional using keyof and in syntax.
Typescript
Need a hint?

Use [K in keyof UserSettings]?: UserSettings[K] to make properties optional.

3
Create a variable using the mapped type
Create a variable called mySettings of type OptionalSettings and set only the theme property to true.
Typescript
Need a hint?

Write const mySettings: OptionalSettings = { theme: true }.

4
Print the variable to see the result
Write a console.log statement to print the mySettings variable.
Typescript
Need a hint?

Use console.log(mySettings) to show the variable.