TypeScript'te satisfies operatörü ne işe yarar? Tip annotation'dan (: Type) farkı nedir?

Cevap

satisfies (TS 4.9+), bir değerin bir tipe uyduğunu kontrol eder ama değerin çıkarılan (inferred) daha dar tipini korur. : Type annotation ise değerin tipini o tipe genişletir ve detay kaybolur.

type Route = { path: string; auth?: boolean };

// Annotation: tip Record<string, Route> olur, anahtarlar kaybolur
const routes1: Record<string, Route> = {
  home: { path: "/" },
  admin: { path: "/admin", auth: true },
};
routes1.hmoe; // Hata yok! (yazım hatası yakalanmaz)

// satisfies: hem kontrol edilir hem anahtarlar korunur
const routes2 = {
  home: { path: "/" },
  admin: { path: "/admin", auth: true },
} satisfies Record<string, Route>;
routes2.hmoe;  // Hata: Property 'hmoe' does not exist
routes2.admin.auth; // tip: boolean

Başka bir klasik örnek:

type Color = string | [number, number, number];
const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
} satisfies Record<string, Color>;

palette.green.toUpperCase();   // OK: string olduğu biliniyor
palette.red.map((n) => n / 255); // OK: tuple olduğu biliniyor

Ne zaman hangisi?

  • Config nesneleri, route tabloları, tema token'ları: `satisfies` (doğrulama + dar tip).
  • Fonksiyon parametreleri ve dönüş tipleri, değişkenin ileride farklı değer alacağı durumlar: annotation.
  • as (type assertion) ise kontrol yapmaz, derleyiciyi susturur; mümkünse kaçının.
  • as const satisfies T birlikte kullanılarak literal tipler korunup aynı zamanda doğrulama yapılabilir.
  1. any, unknown ve never tipleri arasındaki fark nedir?OrtaTypeScriptFrontend
  2. Generic (jenerik) tipler nedir? Bir örnekle açıklayın.OrtaTypeScriptFrontend
  3. interface ile type alias arasındaki farklar nelerdir?OrtaTypeScriptFrontend
  4. TypeScript nedir, JavaScript'e göre avantajları nelerdir?KolayTypeScriptFrontend
  5. tsconfig.json'daki strict modu neleri açar, neden önemlidir?OrtaTypeScriptFrontend
  6. TypeScript'te enum ile union literal tip arasında hangisini tercih edersiniz?KolayTypeScriptFrontend

Bu konuda başka bir soru biliyor musun?

Mülakatta karşılaştığın soruları ekle, onaylandıktan sonra yayına alınsın.

Soru ekle