DOM की Type Definitions
In this page:
const element: HTMLElementType = document.createElement("tagName");
element.propertyName = value;
Document Type
Document type उस single document object को describe करता है जो हर page को access होता है, elements query और create करने वाले इसके methods सहित, और यह बिना किसी extra install के TypeScript की DOM library में built-in आता है।
उदाहरण: Document Type
const heading: HTMLElement = document.createElement("h1");
heading.textContent = "Hello";
console.log(heading.tagName);
HTMLElement Type
HTMLElement DOM tree में किसी भी element के लिए general base type है, style, className, और addEventListener जैसी shared properties expose करते हुए जो हर तरह का element common रूप से रखता है।
उदाहरण: HTMLElement Type
const el: HTMLElement = document.createElement("div");
el.className = "box";
el.style.color = "blue";
console.log(el.className, el.style.color);
Specific Element Types
HTMLInputElement या HTMLButtonElement जैसे ज़्यादा specific element types HTMLElement को उस tag के लिए unique properties के साथ extend करते हैं, जैसे inputs पर .value, इसलिए सही specific type में cast करना सही specific properties unlock करता है।
उदाहरण: Specific Element Types
const input: HTMLInputElement = document.createElement("input");
input.value = "hello";
console.log(input.value);
DOM Collections
NodeList और HTMLCollection जैसे DOM collection types elements के groups represent करते हैं जो querySelectorAll जैसे methods से return होते हैं, और वे इसमें थोड़ा अलग होते हैं कि वे live-updating हैं या नहीं और कौन से array methods directly support करते हैं।
उदाहरण: DOM Collections
const container = document.createElement("div");
container.innerHTML = "<p>One</p><p>Two</p>";
const paragraphs: NodeListOf<HTMLParagraphElement> = container.querySelectorAll("p");
console.log(paragraphs.length);
Why DOM Types Matter
any के बजाय सही DOM types उपयोग करने का मतलब है कि compiler mistakes पकड़ता है जैसे किसी ऐसे element पर .value पढ़ना जो असल में एक input नहीं है, उस bug के browser में एक runtime crash के रूप में सामने आने से कहीं पहले।
उदाहरण: Why DOM Types Matter
const input: HTMLInputElement = document.createElement("input");
input.value = "42";
// input.value is known to be a string, caught at compile time
console.log(input.value.length);
- हर चीज़ को
HTMLElementके रूप में type करना और फिर.valueaccess करना, जो सिर्फHTMLInputElementपर मौजूद है। ElementऔरHTMLElementको confuse करना, क्योंकिElementमेंstyleजैसी properties नहीं होती।- Node में DOM code
lib: ["dom"]या एक DOM के बिना चलाना, जहांdocumentundefined या untyped है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: