Ba’zan TypeScript o‘zgaruvchining aniq type ni bilmaydi, lekin siz bilasiz. Shunda biz Type Casting (Type Assertion) ishlatamiz.

📌 Muammo

Masalan:

const inputEl = document.getElementById("user-name")

TypeScript buni shunday ko‘radi:

HTMLElement | null

📌 Muammo nima?

inputEl.value // ❌ error

Chunki:

  • HTMLElement da value yo‘q
  • null bo‘lishi ham mumkin

📌 Yechim — Type Casting

Biz TypeScript ga aniq aytamiz:

“Bu aslida input element”


📌 1-usul (angle bracket)

const inputEl = <HTMLInputElement> document.getElementById("user-name")

📌 2-usul (as keyword) — tavsiya etiladi ✅

const inputEl = document.getElementById("user-name") as HTMLInputElement

📌 Endi ishlaydi:

inputEl.value // ✅

📌 Bu nima qiladi?

as HTMLInputElement

👉 TypeScript ga:

“Buni HTMLInputElement deb hisobla”


📌 MUHIM ⚠️

Type Casting: ❗ type ni tekshirmaydi ❗ faqat ishonadi Agar xato bo‘lsa:

const el = document.getElementById("box") as HTMLInputElement el.value // ❌ runtime error bo‘lishi mumkin

📌 Qachon ishlatiladi?

Type casting ishlatiladi agar:

  • siz type ni TypeScriptdan ko‘ra yaxshiroq bilsangiz
  • DOM bilan ishlaganda (input, button, etc.)
  • API response da aniq type bo‘lsa

📌 Type Casting + null muammo

Agar element topilmasligi mumkin bo‘lsa:

const inputEl = document.getElementById("user-name") as HTMLInputElement

Bu xavfli ⚠️

📌 Xavfsiz variant:

const inputEl = document.getElementById("user-name") if (inputEl) { (inputEl as HTMLInputElement).value }

yoki:

const inputEl = document.getElementById("user-name") as HTMLInputElement | null

📌 Qisqa variant (! bilan)

const inputEl = document.getElementById("user-name")! as HTMLInputElement

🎯 Xulosa

Type Casting — bu:

TypeScript ga “bu qiymat aslida shu type” deb aytish


📌 Misol:

const inputEl = document.getElementById("user-name") as HTMLInputElement inputEl.value

💡 Esda tuting:

  • as → tavsiya etiladi
  • noto‘g‘ri ishlatilsa → runtime error beradi
  • faqat ishonchingiz bo‘lsa ishlating