CodeBlanks Logo Icon CodeBlanks

Summary - Mapped types

Write your own utility type with mapped types.

Summary - Mapped types

Mapped types iterate over a type's properties and transform each one. With [K in keyof T]: T[K] you copy properties; readonly makes them immutable; ? makes them optional. Combining the three you can write your own utility types.

type Guvenli<T> = {
  readonly [K in keyof T]?: T[K];
};

Practice Your own utility type

Write the mapped type Guvenli<T> as { readonly [K in keyof T]?: T[K] }. Define interface Ayar with tema: string and ses: number. Define type GuvenliAyar as Guvenli<Ayar>. Assign { tema: "koyu" } to a variable a (of type GuvenliAyar). Print a.tema with console.log.

Starter code

index.ts
// Guvenli<T> mapped type tanımla
// T'nin tüm özelliklerini hem readonly hem isteğe bağlı yap
// Ayar arayüzünü tema ve ses ile tanımla
// GuvenliAyar türünü Guvenli<Ayar> olarak tanımla
// a değişkenine yalnızca tema içeren nesneyi ata
// tema değerini yazdır

Sample solution

index.ts
type Guvenli<T> = {
  readonly [K in keyof T]?: T[K];
};
interface Ayar {
  tema: string;
  ses: number;
}
type GuvenliAyar = Guvenli<Ayar>;
const a: GuvenliAyar = { tema: "koyu" };
console.log(a.tema);

Expected output

koyu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 You want both immutability and optionality in a mapped type. Which form is correct?

  • { [K in keyof T]: T[K]? readonly }
  • { [readonly K in keyof T]?: T[K] }
  • { [K in keyof T]: readonly T[K] }
  • { readonly [K in keyof T]?: T[K] } Correct answer

Explanation: readonly goes before the square brackets and ? goes right after. This way each property is both immutable and optional. The other forms are syntax errors.

2 Combined mapped type body

Question
type Guvenli<T> = {
  ____ [K in keyof T]?: T[K];
};
Answer
type Guvenli<T> = {
  readonly [K in keyof T]?: T[K];
};

Explanation: To make all properties immutable you write readonly before the square brackets. ? already handles optionality; optional is not a keyword; static and const serve other purposes.

3 Match mapped type transforms

Term Meaning
[K in keyof T]: T[K] Copies all properties as-is
readonly [K in keyof T]: T[K] Makes all properties immutable
[K in keyof T]?: T[K] Makes all properties optional
readonly [K in keyof T]?: T[K] Both immutable and optional

All lessons in Intermediate