as
TypeScript'da as kalit so'zi amalda: event.target, qavslar va ustuvorlik, kengaytirish va toraytirish, literal type'larni saqlash, reduce, satisfies bilan taqqoslash va catch'da as Error xatosi.
38-dars
as
Type assertion g'oyasini ko'rdik. Endi as kalit so'zi amalda qayerda va qanday yoziladi — shunga to'xtalamiz. Eng ko'p uchraydigan joylardan biri — event'lar:
// ❌ Muammo: event.target'ning type'i juda umumiy
const input = document.querySelector("#search")!;
input.addEventListener("input", (e) => {
console.log(e.target.value);
// ❌ 'e.target' is possibly 'null'.
console.log(e.target?.value);
// ❌ Property 'value' does not exist on type 'EventTarget'.
});
e.target — event'ni chiqargan narsa. U input ham, button ham, hatto window ham bo'lishi mumkin, shuning uchun TS unga eng umumiy EventTarget | null type'ini beradi.
// ✅ Yechim: target'ning aniq type'ini as bilan ko'rsatamiz
input.addEventListener("input", (e) => {
const target = e.target as HTMLInputElement;
console.log(target.value); // ✅
});
Qanday ishlaydi?
1. Qavslar va ustuvorlik
as nuqta (.) dan "zaifroq" — u butun ifodaga qo'llanadi. Shuning uchun assertion'dan keyin darhol property olish uchun qavs kerak.
// ✅ Qavs bilan — avval assertion, keyin .value
const value = (e.target as HTMLInputElement).value;
// ✅ Yoki alohida o'zgaruvchiga olib
const target = e.target as HTMLInputElement;
const value2 = target.value;
Qavssiz e.target as HTMLInputElement.value yozilsa, TS uni "HTMLInputElement.value degan type" deb tushunadi va xato beradi. Qaysi usul o'qilishi osonroq bo'lsa, o'shani tanlang — bitta joyda ishlatilsa qavs, ko'p joyda bo'lsa alohida o'zgaruvchi.
2. Ikki yo'nalish: kengaytirish va toraytirish
as ikki tomonga ishlaydi, lekin xavf darajasi har xil.
type Status = "idle" | "loading" | "done";
// Kengaytirish (aniq → umumiy) — xavfsiz
const s = "idle" as Status; // "idle" haqiqatan Status ichida
const el = document.body as HTMLElement; // body haqiqatan HTMLElement
// Toraytirish (umumiy → aniq) — xavfli
const t = e.target as HTMLInputElement; // target input bo'lmasligi ham mumkin
| Yo'nalish | Misol | Xavf | Nima uchun |
|---|---|---|---|
| Kengaytirish | "idle" as Status |
✅ xavfsiz | qiymat doim type ichida |
| Toraytirish | EventTarget as HTMLInputElement |
⚠️ xavfli | runtime'da boshqa narsa bo'lishi mumkin |
| Bog'liq bo'lmagan | string as number |
❌ TS ruxsat bermaydi | type'lar bir-biriga umuman sig'maydi |
Kengaytirish uchun ko'pincha as shart ham emas — annotation (const s: Status = "idle") yetarli va yaxshiroq.
3. Literal type'larni saqlab qolish
Obyekt ichidagi string qiymat avtomatik stringga kengayadi. Funksiya aniq literal kutsa, xato chiqadi.
type Method = "GET" | "POST";
function request(url: string, method: Method) {}
const options = { url: "/users", method: "GET" }; // method: string
request(options.url, options.method);
// ❌ Argument of type 'string' is not assignable to parameter of type 'Method'.
// ✅ 1-usul: faqat bitta qiymatga as const
const options1 = { url: "/users", method: "GET" as const }; // method: "GET"
// ✅ 2-usul: butun obyektga as const (barcha field'lar readonly bo'ladi)
const options2 = { url: "/users", method: "GET" } as const;
// ✅ 3-usul: annotation — ko'pincha eng toza yechim
const options3: { url: string; method: Method } = { url: "/users", method: "GET" };
as const yolg'on gapirmaydi — qiymat haqiqatan "GET", shuning uchun bu asning eng xavfsiz ishlatilishi.
4. Bo'sh boshlang'ich qiymat: reduce
reducega bo'sh obyekt yoki massiv berilsa, TS uning type'ini {} yoki never[] deb oladi va keyinchalik unga hech narsa qo'sha olmaydi.
const words = ["olma", "nok", "olma"];
const counts = words.reduce((acc, word) => {
acc[word] = (acc[word] ?? 0) + 1;
// ❌ Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
// No index signature with a parameter of type 'string' was found on type '{}'.
return acc;
}, {});
// ✅ Boshlang'ich qiymatga type beramiz (index signature, 18-dars)
const counts = words.reduce((acc, word) => {
acc[word] = (acc[word] ?? 0) + 1;
return acc;
}, {} as { [word: string]: number });
counts["olma"]; // number
Bu asning qonuniy ishlatilishi: bo'sh {} hali hech qanday field'ga ega emas va keyinchalik to'ldiriladi. Xuddi shu ishni generic bilan ham qilish mumkin.
5. as va satisfies
Ko'p hollarda as o'rniga satisfies operatori yaxshiroq: u qiymatni type'ga qarab tekshiradi, lekin type'ni kengaytirib yubormaydi.
type Config = { host: string; port: number };
const c1 = { host: "localhost" } as Config;
// TS jim — 🐛 port yo'q
const c2 = { host: "localhost" } satisfies Config;
// ❌ Property 'port' is missing in type '{ host: string; }' but required in type 'Config'.
satisfiesning annotation'dan ham ustun bo'lgan joyi — aniq type saqlanib qoladi:
type Routes = { [name: string]: string };
const r1: Routes = { home: "/", about: "/about" };
r1.contact; // 🐛 TS jim — type: string, aslida undefined
const r2 = { home: "/", about: "/about" } satisfies Routes;
r2.contact;
// ❌ Property 'contact' does not exist on type '{ home: string; about: string; }'.
: Type |
as Type |
satisfies Type |
|
|---|---|---|---|
| Qiymatni tekshiradimi | ✅ | ❌ (faqat yaqinlik) | ✅ |
| Natija type'i | Type (keng) |
Type (keng) |
qiymatning aniq type'i |
| Asosiy ishlatilishi | o'zgaruvchilar, parametrlar | TS bilmaydigan narsa | config, konstanta obyektlar |
Eng ko'p uchraydigan xato
catch blokida xatoni as Error bilan type'lash.
async function loadUsers() {
try {
await fetchUsers();
} catch (error) {
console.log(error.message);
// ❌ 'error' is of type 'unknown'.
}
}
Dasturchi xatoni tezda yo'qotadi:
try {
await fetchUsers();
} catch (error) {
console.log((error as Error).message); // 🐛 TS jim
}
Nega bunday bo'ladi? Strict rejimda catch ichidagi o'zgaruvchi unknown, chunki JavaScript'da throw istalgan narsani otishi mumkin: throw "xato", throw 404, throw { code: 1 }. Ko'pincha bu haqiqatan Error bo'ladi, shuning uchun as Error ishlaganday tuyuladi. Lekin biror kutubxona yoki eski kod string otsa:
try {
throw "Ulanish uzildi"; // Error emas, oddiy string
} catch (error) {
console.log((error as Error).message); // undefined — xabar yo'qoldi
}
Hech qanday xato chiqmaydi — foydalanuvchiga yoki log'ga shunchaki undefined yoziladi va asl sabab yo'qoladi.
// ✅ 1-yechim: instanceof bilan narrowing
try {
await fetchUsers();
} catch (error) {
if (error instanceof Error) {
console.log(error.message); // error: Error
} else {
console.log(String(error)); // string, number va boshqalar
}
}
// ✅ 2-yechim: qayta ishlatiladigan yordamchi funksiya
function getErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
try {
await fetchUsers();
} catch (error) {
console.log(getErrorMessage(error)); // ✅ har qanday holatda ishlaydi
}
Esda tuting: as qiymatni tekshirmaydi, faqat TS'ni jim qiladi — runtime'da boshqa narsa kelishi mumkin bo'lgan joyda as o'rniga narrowing ishlating.