CodeBlanks Logo Icon CodeBlanks

Optional mapped type

Learn to make properties optional with a mapped type.

Optional mapped type

With a mapped type you can make all of T's properties optional. Writing { [K in keyof T]?: T[K] } marks each property with ?; a missing value can be undefined. This is the basis of the Partial utility type.

type Kismi<T> = {
  [K in keyof T]?: T[K];
};
interface Uye { ad: string; yas: number; }
const u: Kismi<Uye> = { ad: "Can" };
// yas can be omitted

Partial data flow

An optional mapped type is especially handy for updates or partial data flows. When only some fields arrive from an API, you use Kismi<T> instead of a type requiring all. The body skips missing fields with an undefined check; type safety is preserved.

Practice Partial member

Write the mapped type Kismi<T> as { [K in keyof T]?: T[K] }. Define interface Uye with ad: string and yas: number. Define type KismiUye as Kismi<Uye>. Assign { ad: "Can" } to a variable u (of type KismiUye). Print u.ad with console.log.

Starter code

index.ts
// Kismi<T> mapped type tanımla
// T'nin tüm özelliklerini isteğe bağlı yap, değer türü aynı kalsın
// Uye arayüzünü ad ve yas ile tanımla
// KismiUye türünü Kismi<Uye> olarak tanımla
// u değişkenine yalnızca ad içeren nesneyi ata
// ad değerini yazdır

Sample solution

index.ts
type Kismi<T> = {
  [K in keyof T]?: T[K];
};
interface Uye {
  ad: string;
  yas: number;
}
type KismiUye = Kismi<Uye>;
const u: KismiUye = { ad: "Can" };
console.log(u.ad);

Expected output

Can

Questions and answers

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

1 Which object is valid as the result of the mapped type below?

index.ts
type Kismi<T> = { [K in keyof T]?: T[K]; };
interface Uye { ad: string; yas: number; }
  • Any subset, including the empty object Correct answer
  • Only an object with the ad property
  • An object whose properties are all numbers
  • Only an object containing every property

Explanation: Because ? makes all properties optional, any subset (including the empty object) is valid. The types do not change; only the requirement is lifted.

2 Add the ? mark

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

Explanation: To make all properties optional in a mapped type, you write ? right after the square brackets. ! forces required; : is already there; readonly adds immutability.

3 Optional mapped type parts

Term Meaning
[K in keyof T]? Makes all properties optional
T[K] Keeps the value type the same
{ ad: "Can" } Valid object with a missing field
type Kismi<T> Optional mapped type alias

All lessons in Intermediate