CodeBlanks Logo Icon CodeBlanks

Summary - Utility types

Write a flexible form type with utility types.

Summary - Utility types

Utility types build new types from existing ones. Partial makes all properties optional, Required makes them required. Pick selects properties, Omit removes them. Record sets up a key-value mapping. Together they let you write flexible form types.

type FormAlan = Pick<Uye, "ad" | "eposta">;
type Guncelleme = Partial<FormAlan>;

Practice Flexible form type

Define interface Uye with ad: string, eposta: string and yas: number. Define type FormTip as Pick<Uye, "ad" | "eposta">. Define type FormGuncelle as Partial<FormTip>. Write function guncelle(u: FormGuncelle): void whose body prints u.ad with console.log if present. Call guncelle({ ad: "Mert" }).

Starter code

index.ts
// Uye arayüzünü ad, eposta, yas ile tanımla
// FormTip türü Uye'dan ad ve eposta özelliklerini alsın
// FormGuncelle türü FormTip'in tüm özelliklerini isteğe_optional yapsın
// guncelle fonksiyonu FormGuncelle parametre alsın
// gövdede u.ad varsa console.log ile yazdır
// { ad: "Mert" } ile çağır

Sample solution

index.ts
interface Uye {
  ad: string;
  eposta: string;
  yas: number;
}
type FormTip = Pick<Uye, "ad" | "eposta">;
type FormGuncelle = Partial<FormTip>;
function guncelle(u: FormGuncelle): void {
  if (u.ad) {
    console.log(u.ad);
  }
}
guncelle({ ad: "Mert" });

Expected output

Mert

Questions and answers

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

1 Which combination takes only <code>ad</code> and <code>eposta</code> from a form and makes them optional?

  • Omit<Partial<Uye>, "eposta">>
  • Partial<Pick<Uye, "ad" | "eposta">> Correct answer
  • Required<Omit<Uye, "ad">>
  • Pick<Record<string, number>, "ad">>

Explanation: First Pick selects ad and eposta, then Partial makes both optional. The others either keep the wrong fields or do not make them optional.

2 Form update type

Question
interface Uye { ad: string; eposta: string; yas: number; }
type FormGuncelle = ____<Pick<Uye, "ad" | "eposta">>;
Answer
interface Uye { ad: string; eposta: string; yas: number; }
type FormGuncelle = Partial<Pick<Uye, "ad" | "eposta">>;

Explanation: To make all selected fields optional you use Partial. Required does the opposite; Omit removes; Record sets up a mapping.

3 Match utility types

Term Meaning
Partial<T> All properties optional
Required<T> All properties required
Pick<T, K> Selects properties in K
Omit<T, K> Removes properties in K

All lessons in Intermediate