0
0
Typescriptprogramming~5 mins

Basic mapped type syntax in Typescript

Choose your learning style9 modes available
Introduction

Mapped types help you create new types by changing each property of an existing type in a simple way.

When you want to make all properties of an object type optional.
When you want to make all properties readonly.
When you want to change the type of all properties in a type.
When you want to create a type that has the same keys but different value types.
Syntax
Typescript
type NewType = {
  [Key in keyof OldType]: NewValueType;
};

keyof OldType gets all keys from the old type.

The Key in keyof OldType part loops over each key.

Examples
This makes all properties of T readonly.
Typescript
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};
This makes all properties of T optional.
Typescript
type Partial<T> = {
  [P in keyof T]?: T[P];
};
This changes all property types to string.
Typescript
type Stringify<T> = {
  [P in keyof T]: string;
};
Sample Program

This program creates a readonly version of the Person type using a mapped type. It then creates a person object with readonly properties. Trying to change a property will cause an error.

Typescript
type Person = {
  name: string;
  age: number;
};

type ReadonlyPerson = {
  readonly [K in keyof Person]: Person[K];
};

const person: ReadonlyPerson = {
  name: "Alice",
  age: 30
};

// person.age = 31; // Error: Cannot assign to 'age' because it is a read-only property

console.log(person.name);
console.log(person.age);
OutputSuccess
Important Notes

Mapped types are a powerful way to transform types without repeating code.

You can add modifiers like readonly or ? inside the mapped type.

Remember, mapped types work on keys of existing types using keyof.

Summary

Mapped types create new types by looping over keys of existing types.

You can change property modifiers or types easily with mapped types.

This helps keep your code DRY and consistent.