0
0
Typescriptprogramming~5 mins

Mapped type modifiers (readonly, optional) in Typescript

Choose your learning style9 modes available
Introduction

Mapped type modifiers let you change properties of an object type all at once. You can make all properties readonly or optional easily.

When you want to make all properties of an object readonly to prevent changes.
When you want to make some or all properties optional for flexibility.
When you want to create a new type based on another but with modified property rules.
When you want to enforce immutability on an object type in your code.
When you want to allow partial updates by making properties optional.
Syntax
Typescript
type NewType = {
  readonly [Key in keyof OldType]: OldType[Key];
};

// or

type NewType = {
  [Key in keyof OldType]?: OldType[Key];
};

readonly before the property makes it unchangeable.

? after the property name makes it optional.

Examples
This makes all properties of Person readonly.
Typescript
type Person = {
  name: string;
  age: number;
};

type ReadonlyPerson = {
  readonly [K in keyof Person]: Person[K];
};
This makes all properties of Person optional.
Typescript
type PartialPerson = {
  [K in keyof Person]?: Person[K];
};
This makes all properties both readonly and optional.
Typescript
type ReadonlyPartialPerson = {
  readonly [K in keyof Person]?: Person[K];
};
Sample Program

This program shows how to make all properties readonly and optional using mapped type modifiers. It also shows that trying to change a readonly property causes 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.name = "Bob"; // Error: Cannot assign to 'name' because it is a read-only property

console.log(person.name);

// Now optional example

type PartialPerson = {
  [K in keyof Person]?: Person[K];
};

const partialPerson: PartialPerson = {
  name: "Charlie"
};

console.log(partialPerson.age);
OutputSuccess
Important Notes

Readonly properties cannot be changed after creation.

Optional properties may be missing or undefined.

You can combine readonly and ? to make properties both readonly and optional.

Summary

Mapped type modifiers let you change all properties of a type at once.

readonly makes properties unchangeable.

? makes properties optional.