0
0
Typescriptprogramming~15 mins

Mapped type modifiers (readonly, optional) in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Mapped type modifiers (readonly, optional)
📖 Scenario: You are working on a simple user profile system. You want to create different versions of a user object: one where all properties are readonly, and another where all properties are optional. This helps you understand how to use mapped type modifiers in TypeScript.
🎯 Goal: Build TypeScript mapped types that make all properties of a user object readonly and another mapped type that makes all properties optional.
📋 What You'll Learn
Create an interface User with exact properties: name (string), age (number), email (string)
Create a mapped type ReadonlyUser that makes all properties of User readonly
Create a mapped type OptionalUser that makes all properties of User optional
Create variables readonlyUser and optionalUser using these mapped types
Print the types of readonlyUser and optionalUser to verify
💡 Why This Matters
🌍 Real World
Mapped types help you create flexible and reusable types in TypeScript, useful when working with APIs or complex data models.
💼 Career
Understanding mapped type modifiers is important for writing safe and maintainable TypeScript code in professional software development.
Progress0 / 4 steps
1
Create the User interface
Create an interface called User 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 list properties with their types inside curly braces.

2
Create the ReadonlyUser mapped type
Create a mapped type called ReadonlyUser that makes all properties of User readonly using the readonly modifier and keyof User.
Typescript
Need a hint?

Use type ReadonlyUser = { readonly [K in keyof User]: User[K] } to make all properties readonly.

3
Create the OptionalUser mapped type
Create a mapped type called OptionalUser that makes all properties of User optional using the ? modifier and keyof User.
Typescript
Need a hint?

Use type OptionalUser = { [K in keyof User]?: User[K] } to make all properties optional.

4
Create variables and print their types
Create a variable called readonlyUser of type ReadonlyUser with values name: "Alice", age: 30, email: "alice@example.com". Create another variable called optionalUser of type OptionalUser with only name: "Bob". Then print both variables using console.log.
Typescript
Need a hint?

Use const readonlyUser: ReadonlyUser = { ... } and const optionalUser: OptionalUser = { ... }. Then print with console.log.