Today! We’re going to continue TypeScript learning like you’re a smart 5-year-old who loves to build things and asks “why?” (which is the best thing ever).
& yes “why?” is my way of learning.
I’ve divided this into 20 Chapters. and will go one by one and each will be of 2 – 3 min. of read.
This is a Continuation. if you have not read the Previous chapter –
Chapter 12
🧩 Chapter 13: Understanding DOM Elements in TypeScript
(aka: How to Make DOM Elements TypeScript safe!)
Imagine you want to grab an field from a webpage, but TypeScript says, “Wait, I’m confused!” 😕 No worries! By the end of this chapter, you’ll know how to tell TypeScript exactly what’s going on🚀
First let’s understand, How to explain to TypeScript what kind of element we’re working with. It’s like giving TypeScript a clear instruction manual! 📖.
🤔 What is Type Assertion?
Type Assertion is like saying to TypeScript:
“Hey, I know this is an
element, so let me use its
value
!”
Two Easy Ways to Do It
Here’s how you can tell TypeScript –
let value = "Karan" as string; // Option 1: Using "as"
OR
let value = <string>"Karan"; // Option 2: Angle brackets
Quick Tip: Use the as
way it’s simpler and works better with React/JSX projects. 😊
😕 Understanding, why we get errors?
Let’s say you try to grab an element and get its value –
const input = document.getElementById("myInput");
console.log(input.value); // ❌ ERROR: Property 'value' does not exist on type 'HTMLElement | null'
What’s the problem?
document.getElementById
returns HTMLElement | null
, which means:
- It could be any HTML element (like ,
, etc.).
- It could be
null
if the element isn’t found.TypeScript’s like, “I don’t know if this is an
or something else!”
🛠️ Fix 1: Tell TypeScript with Type Assertion
Let’s make it clear for TypeScript:
const input = document.getElementById("myInput") as HTMLInputElement; console.log(input.value); // ✅ Works perfectly!
By adding
as HTMLInputElement
, we’re saying, “This is an!” Now TypeScript lets us use properties like
value
,type
, orchecked
without any issues.🚨 Fix 2: Handling
null
Safely
What if
getElementById
can’t find the element? It returnsnull
, and trying to use.value
onnull
will break your code. Let’s keep things safe:Option A: Check with
if
const el = document.getElementById("myInput"); if (el) { const input = el as HTMLInputElement; console.log(input.value); // ✅ Safe and happy }
Option B: Use Optional Chaining (Quick and Easy)
const input = document.getElementById("myInput") as HTMLInputElement | null; console.log(input?.value); // ✅ Won’t break if input is null
Quick Tip: The
if
check is safer, but optional chaining (?.
) is great for quick scripts. Pick what feels right! 😄📋 Your DOM Type Guide Sheet
Here’s a simple list of common HTML elements and their TypeScript types!⚡️ (You don’t need to save it, but it’ll give you a good understanding of HTML Types)
HTML Element TypeScript Type What It’s For HTMLInputElement
Text boxes, checkboxes, radios HTMLTextAreaElement
Big text areas HTMLSelectElement
Dropdown menus HTMLOptionElement
Choices in a dropdown HTMLButtonElement
Clickable buttons HTMLFormElement
Forms for user input HTMLLabelElement
Labels for form fields HTMLImageElement
Pictures HTMLAnchorElement
Links /HTMLDivElement
/HTMLSpanElement
Basic containers HTMLCanvasElement
Drawing or animations HTMLVideoElement
Video players HTMLAudioElement
Audio players HTMLIFrameElement
Embedded content HTMLTableElement
Tables HTMLTableRowElement
Table rows / HTMLTableCellElement
Table cells HTMLUListElement
/HTMLOListElement
Lists (bullet or numbered) HTMLLIElement
List items 👉🏻 You can now safely access HTML properties.
Read Previous Chapters
If you enjoyed this and want to master TypeScript and other technologies, follow the series and drop a like!🤝
Bonus Read
How i created my own State Management Library : Rethinking State Management in React — From a Dev, for Developers. - It could be