DOM Elements की Type Casting
In this page:
const element = document.getElementById("id") as HTMLInputElement;
const other = <HTMLInputElement>document.getElementById("id");
as से Cast करना
as keyword compiler को एक value को उससे ज़्यादा specific type के रूप में treat करने के लिए कहता है जो इसने infer किया था, जो यह है कि आप एक generic Element को HTMLInputElement जैसे एक concrete type में कैसे बदलते हैं जब आपको DOM structure पर भरोसा हो।
उदाहरण: Casting with as
const el = document.createElement("input") as HTMLInputElement;
el.value = "typed";
console.log(el.value);
querySelector Results Cast करना
querySelector के result को as HTMLButtonElement से cast करना एक आम pattern है क्योंकि querySelector का return type अकेले button-specific properties जैसे .disabled expose करने के लिए बहुत generic है।
उदाहरण: Casting querySelector Results
document.body.innerHTML = '<button class="submit" disabled></button>';
const btn = document.querySelector(".submit") as HTMLButtonElement;
console.log(btn.disabled);
Cast करने से पहले Check करना
Input-specific properties छूने से पहले runtime पर एक element का असल type check करना — उदाहरण के लिए instanceof HTMLInputElement से — आपको वह असली safety देता है जो एक blind as cast नहीं देता, क्योंकि check असल में gracefully fail हो सकता है।
उदाहरण: Checking Before Casting
const el: Element = document.createElement("input");
if (el instanceof HTMLInputElement) {
console.log(el.value);
}
Non-Null Assertions
एक non-null assertion (element!) compiler को बताता है कि यह worry करना बंद कर दे कि एक value null हो सकता है, जो convenient है लेकिन dangerous, क्योंकि यह एक असली check suppress करता है जिसे runtime आप गलत होने पर भी enforce करता रहेगा।
उदाहरण: Non-Null Assertions
document.body.innerHTML = '<div id="app"></div>';
const el = document.getElementById("app")!;
console.log(el.id);
Unsafe Casts से बचना
एक ऐसे type में cast करने से बचें जो DOM structure से असल में guaranteed नहीं है — एक incorrect as cast cleanly compile होता है लेकिन failure को .value या इसी तरह की एक runtime crash में shift कर देता है, exactly वही class of bug जिसे रोकने के लिए static typing मौजूद है।
उदाहरण: Avoiding Unsafe Casts
const el = document.createElement("div") as unknown as HTMLInputElement;
// This compiles cleanly but el.value doesn't really exist on a div at runtime.
console.log((el as any).value);
- किसी ऐसी चीज़ पर
as HTMLInputElementउपयोग करना जो input नहीं है, जो error को छुपाता है और runtime पर fail होता है। querySelectorके बाद!assertion ज़्यादा उपयोग करना, जो element missing होने पर एकTypeErrorके साथ crash करता है।- एक unrelated type में cast करना जैसे
el as number, जिसे TypeScript insufficient overlap के रूप में reject करता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: