Series: TypeScript Basics Lesson 82

DOM element typing

TypeScript'da DOM elementlarini type'lash: querySelector generic bilan, teg nomidan avtomatik type, instanceof bilan xavfsiz tekshirish, login forma misoli va ko'p ishlatiladigan element type'lari.

82-dars

DOM element typing

HTML elementlarning har biri uchun TypeScript'da tayyor type bor: HTMLInputElement, HTMLButtonElement, HTMLDivElement va h.k. To'g'ri type'ni bilsangiz, .value, .checked, .disabled kabi xususiyatlardan xavfsiz foydalanasiz.

Muammo

const input = document.getElementById("email");
input.value;
// ❌ 'input' is possibly 'null'.
// ❌ Property 'value' does not exist on type 'HTMLElement'.

Ikki sabab:

  • getElementById HTMLElement | null qaytaradi, element topilmasligi mumkin.
  • Oddiy HTMLElement'da .value yo'q, u faqat HTMLInputElement'da bor.

1-yechim: querySelector + generic

const input = document.querySelector<HTMLInputElement>("#email");

if (input) {
  input.value; // ✅ string
}

2-yechim: teg nomi bilan, type avtomatik

const btn = document.querySelector("button");
// type: HTMLButtonElement | null (TS o'zi biladi)

const img = document.querySelector("img");
// type: HTMLImageElement | null

Teg nomini ("button", "img") bersangiz, TS type'ni o'zi aniqlaydi. "#id" yoki ".class" bersangiz, aniqlay olmaydi (natija Element | null bo'ladi), shunda generic kerak.

3-yechim: instanceof bilan tekshirish (eng xavfsiz)

const el = document.getElementById("email");

if (el instanceof HTMLInputElement) {
  el.value; // ✅ runtime'da ham tekshirildi
}

as HTMLInputElement'dan farqli o'laroq (37-dars), bu haqiqatan tekshiradi. as faqat TS'ni jim qiladi, instanceof esa runtime'da element rostdan inputmi — shuni ko'radi.

Real misol: login forma

const form = document.querySelector<HTMLFormElement>("#login-form");
const email = document.querySelector<HTMLInputElement>("#email");
const remember = document.querySelector<HTMLInputElement>("#remember");
const submitBtn = document.querySelector<HTMLButtonElement>("#submit");

if (!form || !email || !remember || !submitBtn) {
  throw new Error("Forma elementlari topilmadi");
}

submitBtn.disabled = true;
console.log(email.value);      // string
console.log(remember.checked); // boolean

throw'dan keyin TS hamma elementlar null emasligini biladi (early return / guard, 41-dars).

Ko'p ishlatiladigan type'lar

Teg Type Asosiy xususiyat
<input> HTMLInputElement value, checked
<textarea> HTMLTextAreaElement value
<select> HTMLSelectElement value, options
<button> HTMLButtonElement disabled
<form> HTMLFormElement reset(), elements
<a> HTMLAnchorElement href
<img> HTMLImageElement src
<div> HTMLDivElement —

Eslab qolish uchun

  • DOM qidiruv doim null qaytarishi mumkin, tekshiring.
  • #id bilan qidirsangiz, generic bering: querySelector<HTMLInputElement>.
  • as o'rniga instanceof xavfsizroq.