0
0
Typescriptprogramming~15 mins

Key remapping with as clause in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Key remapping with as clause
📖 Scenario: Imagine you have a list of users with their full names and ages. You want to create a new list where the keys are changed to shorter, friendlier names.
🎯 Goal: You will create a new array of objects by remapping the keys of the original user objects using TypeScript's key remapping with as clause.
📋 What You'll Learn
Create an array called users with objects having keys fullName and age
Create a type alias ShortUser that remaps fullName to name and keeps age
Create a new array shortUsers by mapping users to objects of type ShortUser
Print the shortUsers array
💡 Why This Matters
🌍 Real World
Key remapping helps when you get data from an API or database with long or unclear keys and want to rename them for easier use in your code.
💼 Career
Understanding key remapping is useful for frontend and backend developers working with TypeScript to keep code clean and maintainable when handling data transformations.
Progress0 / 4 steps
1
Create the initial users array
Create an array called users with these exact objects: { fullName: "Alice Johnson", age: 30 }, { fullName: "Bob Smith", age: 25 }, and { fullName: "Charlie Brown", age: 35 }.
Typescript
Need a hint?

Use const users = [ ... ] with the exact objects inside.

2
Create the ShortUser type with key remapping
Create a type alias called ShortUser that remaps the key fullName to name and keeps the age key as is, using TypeScript's key remapping with as clause.
Typescript
Need a hint?

Use type ShortUser = { [K in keyof typeof users[0] as K extends "fullName" ? "name" : K]: typeof users[0][K] }.

3
Map users to shortUsers with remapped keys
Create a new array called shortUsers by mapping over users and returning objects with keys name (from fullName) and age. Use the ShortUser type for the new objects.
Typescript
Need a hint?

Use const shortUsers: ShortUser[] = users.map(user => ({ name: user.fullName, age: user.age })).

4
Print the shortUsers array
Write a console.log statement to print the shortUsers array.
Typescript
Need a hint?

Use console.log(shortUsers) to show the new array.