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: booleanBaş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 biliniyorNe 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 Tbirlikte kullanılarak literal tipler korunup aynı zamanda doğrulama yapılabilir.
İlgili TypeScript soruları
- any, unknown ve never tipleri arasındaki fark nedir?
- Generic (jenerik) tipler nedir? Bir örnekle açıklayın.
- interface ile type alias arasındaki farklar nelerdir?
- TypeScript nedir, JavaScript'e göre avantajları nelerdir?
- tsconfig.json'daki strict modu neleri açar, neden önemlidir?
- TypeScript'te enum ile union literal tip arasında hangisini tercih edersiniz?
Bu konuda başka bir soru biliyor musun?
Mülakatta karşılaştığın soruları ekle, onaylandıktan sonra yayına alınsın.