tezvyn:

Type-Safe DOM Selection in TypeScript

Source: typescriptlang.orgbeginner

TypeScript knows DOM types but can't guarantee an element exists. Selecting an element returns `Type | null`, forcing you to handle the `null` case. This prevents runtime errors when your script runs before the DOM element loads.

TypeScript provides built-in types for the DOM, but it can't know if your HTML actually contains a specific element. Functions like `getElementById` return a union type, `HTMLElement | null`, to reflect this uncertainty at compile time. This is central to all frontend TypeScript, from mounting a React app to attaching event listeners. The footgun is forgetting the `null` check, which the compiler enforces to prevent common runtime errors like "Cannot read properties of null".

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Type-Safe DOM Selection in TypeScript · Tezvyn