Type assertions
TypeScript'da type assertion: as sintaksisi, runtime'da hech narsa qilmasligi, yaqin type'lar qoidasi, annotation va narrowing bilan farqi, as const va {} as Type xatosi.
37-dars
Type assertions
Ba'zan dasturchi qiymat haqida TS'dan ko'proq narsa biladi. Masalan, HTML'da id="email" element <input> ekanini siz bilasiz, lekin TS faqat umumiy HTMLElement deb biladi.
// ❌ Muammo: TS element turini bilmaydi
const input = document.getElementById("email");
console.log(input.value);
// ❌ 'input' is possibly 'null'.
console.log(input?.value);
// ❌ Property 'value' does not exist on type 'HTMLElement'.
getElementById istalgan element qaytarishi mumkin (div, button, input...), shuning uchun TS eng umumiy HTMLElement | null type'ini beradi. value esa faqat input kabi elementlarda bor.
// ✅ Yechim: type assertion — "bu aslida HTMLInputElement" deymiz
const input = document.getElementById("email") as HTMLInputElement;
console.log(input.value); // ✅ input: HTMLInputElement
Type assertion — TS'ga "menga ishon, bu qiymatning type'i aslida shunday" deyish. U tekshiruv emas, va'da.
Qanday ishlaydi?
1. Ikki xil sintaksis
const el1 = document.getElementById("email") as HTMLInputElement; // as sintaksisi
const el2 = <HTMLInputElement>document.getElementById("email"); // burchakli qavs sintaksisi
Ikkalasi bir xil ishlaydi, lekin .tsx fayllarda (React) burchakli qavs JSX teglari bilan aralashib ketadi va ishlamaydi. Shuning uchun amalda doim as ishlatiladi.
2. Runtime'da hech narsa qilmaydi
Assertion faqat TS uchun. Kompilyatsiyadan keyin u butunlay o'chib ketadi — qiymat o'zgarmaydi, tekshirilmaydi, aylantirilmaydi.
// TypeScript
const input = document.getElementById("email") as HTMLInputElement;
// Kompilyatsiyadan keyingi JavaScript
const input = document.getElementById("email");
🐛 Shuning uchun HTML'da email id'li element yo'q bo'lsa yoki u <div> bo'lsa, TS hech narsa demaydi, lekin runtime'da xato chiqadi:
const input = document.getElementById("emial") as HTMLInputElement; // id'da imlo xatosi
console.log(input.value); // 💥 Cannot read properties of null (reading 'value')
Assertion null holatini ham "yo'q qilib" yubordi — aslida u hali ham mumkin.
3. Faqat "yaqin" type'lar orasida ruxsat
TS butunlay bog'liq bo'lmagan type'ga assertion qilishga yo'l qo'ymaydi. Ruxsat faqat bir type ikkinchisiga sig'sa beriladi: kengdan torga yoki tordan kengga.
const text = "42";
const n = text as number;
// ❌ Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
const body = document.createElement("body"); // HTMLBodyElement
const el = body as HTMLElement; // ✅ HTMLBodyElement → kengroq HTMLElement
const div = body as HTMLDivElement; // ❌ ikkalasi ham HTMLElement, lekin biri ikkinchisiga sig'maydi
Xato xabari "aylanma yo'l"ni ham aytadi: avval unknownga (7-dars), keyin kerakli type'ga.
const n = text as unknown as number; // TS jim
n.toFixed(2); // 💥 runtime: n.toFixed is not a function — n hali ham "42" string
🐛 Bu "ikki marta assertion" TS himoyasini butunlay o'chiradi. U faqat juda kam, chindan zarur holatlarda ishlatiladi. String'ni songa aylantirish uchun esa Number(text) kerak — assertion aylantirmaydi.
4. Assertion va annotation farqi
Bir qarashda ikkalasi o'xshash, lekin annotation tekshiradi, assertion esa ishonadi.
type User = { name: string; age: number };
const a: User = { name: "Ali" };
// ❌ Property 'age' is missing in type '{ name: string; }' but required in type 'User'.
const b = { name: "Ali" } as User; // TS jim — 🐛 age yo'q, lekin type'da bor
Annotation : User |
Assertion as User |
|
|---|---|---|
| Qiymatni type'ga qarab tekshiradimi | ✅ to'liq | ❌ faqat "yaqinlik"ni |
| Yetishmayotgan field'larni topadimi | ✅ | ❌ |
| Ortiqcha field'larni topadimi | ✅ | ❌ |
| Qachon ishlatiladi | deyarli doim | TS bila olmaydigan narsani bilsangiz |
Qoida oddiy: annotation yozish mumkin bo'lsa, assertion yozmang.
5. Assertion va narrowing farqi
Narrowing runtime'da haqiqiy tekshiruv qiladi, TS esa shu tekshiruvga qarab type'ni toraytiradi. Assertion hech narsani tekshirmaydi.
const el = document.getElementById("email");
// Assertion — ishonch
const a = el as HTMLInputElement;
a.value; // TS jim, lekin el null yoki div bo'lsa — 💥
// Narrowing — tekshiruv
if (el instanceof HTMLInputElement) {
el.value; // ✅ bu yerda el haqiqatan input ekani tekshirilgan
}
6. as const — maxsus holat
as const boshqa assertion'lardan farq qiladi: u TS'ni aldamaydi, aksincha type'ni eng tor holatga keltiradi — literal type'lar va readonly.
const dirs1 = ["up", "down"]; // string[]
const dirs2 = ["up", "down"] as const; // readonly ["up", "down"]
const config = { mode: "dark" } as const; // { readonly mode: "dark" }
config.mode = "light";
// ❌ Cannot assign to 'mode' because it is a read-only property.
as const xavfsiz, chunki qiymat haqiqatan ham aynan shu. U literal type'lar bilan ishlashda tez-tez kerak bo'ladi.
Eng ko'p uchraydigan xato
Obyektni {} as Type bilan boshlab, keyin to'ldirish.
type User = { name: string; age: number; email: string };
const user = {} as User; // TS jim
user.name = "Ali";
user.age = 25;
// email unutildi
sendEmail(user.email.toLowerCase());
// 💥 runtime: Cannot read properties of undefined (reading 'toLowerCase')
Nega bunday bo'ladi? Annotation bilan const user: User = {} yozilsa, TS darhol xato beradi, chunki bo'sh obyektda majburiy field'lar yo'q. Dasturchi bu xatoni "yo'qotish" uchun as User yozadi va obyektni keyinroq to'ldirishni rejalashtiradi. Lekin asdan keyin TS obyektni allaqachon to'liq User deb hisoblaydi va qaysi field'lar haqiqatan qo'shilganini kuzatmaydi. Bitta field unutilsa — xato faqat runtime'da chiqadi.
// ✅ 1-yechim: obyektni birdaniga, annotation bilan yaratish
const user: User = {
name: "Ali",
age: 25,
email: "[email protected]",
};
// email unutilsa: ❌ Property 'email' is missing in type '{ name: string; age: number; }' but required in type 'User'.
// ✅ 2-yechim: qiymatlarni avval o'zgaruvchilarda tayyorlab, keyin obyekt yig'ish
const name = getName();
const age = getAge();
const email = getEmail();
const user2: User = { name, age, email };
Esda tuting: as TS'ning tekshiruvini o'chiradi, xatoni emas — annotation yozish mumkin bo'lgan joyda assertion ishlatmang.