0
0
Typescriptprogramming~30 mins

Mapped type with conditional types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Mapped type with conditional types
📖 Scenario: You are working on a TypeScript project where you want to create a new type that changes the properties of an existing type based on their value types.For example, you want to make all string properties optional and keep other properties required.
🎯 Goal: Build a mapped type using conditional types that makes all string properties optional and leaves other properties required.
📋 What You'll Learn
Create an interface called Person with properties name (string), age (number), and email (string).
Create a mapped type called OptionalStrings that makes string properties optional and keeps other properties required.
Create a variable person1 of type OptionalStrings and assign it an object with age and email properties.
Print the person1 object to the console.
💡 Why This Matters
🌍 Real World
Mapped types with conditional types help you create flexible and reusable types in TypeScript, useful when working with APIs or complex data models.
💼 Career
Understanding mapped and conditional types is important for TypeScript developers to write clean, maintainable, and type-safe code in professional projects.
Progress0 / 4 steps
1
Create the initial interface
Create an interface called Person with these exact properties: name of type string, age of type number, and email of type string.
Typescript
Need a hint?

Use the interface keyword and define the properties with their types inside curly braces.

2
Create the mapped type with conditional types
Create a mapped type called OptionalStrings that iterates over the keys of Person. Use a conditional type to make properties of type string optional and keep other properties required.
Typescript
Need a hint?

Use [K in keyof Person] to loop over keys and a conditional type with extends string to check the property type.

3
Create a variable using the mapped type
Create a variable called person1 of type OptionalStrings and assign it an object with age set to 30 and email set to "test@example.com". Do not include name property.
Typescript
Need a hint?

Remember that string properties are optional, so you can omit name.

4
Print the variable to the console
Write a console.log statement to print the person1 object.
Typescript
Need a hint?

Use console.log(person1) to display the object.