0
0
Typescriptprogramming~20 mins

Mapped type with template literals in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Mapped type with template literals
📖 Scenario: You are working on a user profile system where you want to create new property names by adding prefixes to existing keys.
🎯 Goal: Create a mapped type that uses template literals to add a prefix to each key of an existing interface.
📋 What You'll Learn
Create an interface called User with keys name and age.
Create a type called PrefixedUser that adds the prefix user_ to each key of User using a mapped type with template literals.
Create a variable prefixedUser of type PrefixedUser with appropriate values.
Print the prefixedUser object.
💡 Why This Matters
🌍 Real World
Adding prefixes or suffixes to keys is useful when integrating with APIs or libraries that require specific naming conventions.
💼 Career
Understanding mapped types and template literals helps in writing flexible and reusable TypeScript code, a valuable skill for frontend and backend developers.
Progress0 / 4 steps
1
Create the User interface
Create an interface called User with two properties: name of type string and age of type number.
Typescript
Need a hint?

Use the interface keyword to define User with the specified properties.

2
Create the PrefixedUser mapped type
Create a mapped type called PrefixedUser that adds the prefix user_ to each key of the User interface using template literals.
Typescript
Need a hint?

Use keyof User to get keys and template literals to add user_ prefix.

3
Create a variable of type PrefixedUser
Create a variable called prefixedUser of type PrefixedUser and assign it an object with keys user_name set to "Alice" and user_age set to 30.
Typescript
Need a hint?

Make sure the keys match the prefixed keys from PrefixedUser.

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

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