tezvyn:

TypeScript & Web APIs

TypeScript, browser APIs, WebAssembly, PWAs

246 bites

More in TypeScript & Web APIs — page 11

Promise Cleanup with .finally()
TypeScript & Web APIs2 min read

Promise Cleanup with .finally()

Promise.finally() is the `try...catch...finally` for async code, guaranteeing logic runs after a promise settles. Use it to hide a loading spinner or close a network connection without duplicating code in `.then()` and `.catch()`.

Typing `fetch` Responses in TypeScript
TypeScript & Web APIs2 min read

Typing `fetch` Responses in TypeScript

The `fetch` promise resolves to a generic `Response`, not your typed data. You must first parse the body with `.json()`, then assert the type of the resulting data. This is essential for all API calls.

TypeScript & Web APIs2 min read

TypeScript Generics: Writing Functions That Adapt to Types

TypeScript generics create functions with type placeholders, capturing an input's type to inform the output's. This is vital for reusable components that work on various data types.

The Promise Constructor: Wrapping Old Callbacks
TypeScript & Web APIs2 min read

The Promise Constructor: Wrapping Old Callbacks

The `Promise` constructor turns old callback-style functions into modern promises you can `await`. Use it to "promisify" APIs like `setTimeout` that don't return promises. The footgun is wrapping already-promise-based code, creating unnecessary complexity.

The Promise Object: A Placeholder for Future Values
TypeScript & Web APIs2 min read

The Promise Object: A Placeholder for Future Values

A Promise is an IOU for a value from an async operation, like a network request. It's a placeholder that will eventually hold a result or an error. Use it for fetching data or reading files. The footgun: always add a `.catch()` to handle failures.

TypeScript & Web APIs2 min read

Callback Hell: Navigating JavaScript's Async Pyramid

Callback Hell is the 'pyramid of doom' structure from nesting async functions. It happens when chaining I/O tasks like API calls, where each step depends on the last. The footgun is writing async code as if it runs sequentially, creating unreadable nests.

currentTarget vs. target: Who's Listening vs. Who Shouted
TypeScript & Web APIs2 min read

currentTarget vs. target: Who's Listening vs. Who Shouted

event.currentTarget is the element listening for an event, while event.target is the element that triggered it. This is vital for event delegation patterns. Be careful: currentTarget is only valid inside the handler and becomes null afterward.

Typed Custom Events: Making Browser Events Type-Safe
TypeScript & Web APIs2 min read

Typed Custom Events: Making Browser Events Type-Safe

CustomEvent lets you fire your own browser events, but its payload is `any`. Typing them means defining a specific shape for the event's `detail` property, turning a generic signal into a predictable, self-documenting API for your components.

The FormData API: From HTML Forms to Typed Objects
TypeScript & Web APIs2 min read

The FormData API: From HTML Forms to Typed Objects

FormData serializes an HTML form into key/value pairs for `fetch`. In TypeScript, its main footgun is that `get()` returns a generic `string | File | null`, requiring you to validate and cast the data before using it safely.

Typing NodeList vs. HTMLCollection in TypeScript
TypeScript & Web APIs2 min read

Typing NodeList vs. HTMLCollection in TypeScript

NodeList can contain any node (elements, text, comments), while HTMLCollection only holds elements. TypeScript forces you to handle this. Use querySelectorAll for a NodeList, or getElementsByTagName for an HTMLCollection.

Strongly-Typed Event Listeners in TypeScript
TypeScript & Web APIs2 min read

Strongly-Typed Event Listeners in TypeScript

TypeScript turns `addEventListener`'s magic strings into a compile-time checked dictionary. It knows a button has a "click" event, preventing typos and inferring the event object's type.

The DOM's Inheritance Chain: EventTarget > Node > Element
TypeScript & Web APIs2 min read

The DOM's Inheritance Chain: EventTarget > Node > Element

Every HTML element is a stack of types: an EventTarget for events, a Node for tree structure, and an Element for common attributes. This lets you write type-safe DOM code, knowing a `div` has properties from all its ancestors.

Accessing data-* Attributes with `dataset`
TypeScript & Web APIs2 min read

Accessing data-* Attributes with `dataset`

The `dataset` property is a live map of an element's `data-*` attributes. It automatically converts HTML `data-user-id` to `element.dataset.userId` in JS, perfect for storing state. The footgun: name conversion is lossy; HTML attributes are always lowercased.

TypeScript & Web APIs2 min read

Type-Safe DOM Selection in TypeScript

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 & Web APIs2 min read

TypeScript Mixins: Building Classes from Reusable Parts

A mixin is a function that takes a class and returns a new one with added features, like bolting on a turbocharger. Use it to share behavior (e.g., logging) across unrelated classes.

TypeScript & Web APIs2 min read

TypeScript Class Access Modifiers

Access modifiers are like privacy settings for class members, controlling what code can see them. Use `public` (default), `private` (class-only), and `protected` (class and subclasses) to enforce encapsulation.

TypeScript & Web APIs2 min read

TypeScript Classes: Blueprints for Typed Objects

A TypeScript class is a blueprint for creating objects, adding type safety to JavaScript's object-oriented patterns. Use them for core data structures like a `User`. The main footgun is forgetting to initialize properties, which strict mode flags as an error.

TypeScript & Web APIs2 min read

TypeScript: Typing Function Inputs and Outputs

Think of function types as a contract defining what data goes in and what comes out. This is core to TypeScript, ensuring functions are called correctly. The footgun is relying on return type inference, which can hide bugs if logic changes unexpectedly.

TypeScript & Web APIs2 min read

TypeScript: Build New String Types with Template Literals

Template literal types are a factory for new string types, built from existing string literals and unions. They are perfect for generating permutations, like creating 'propChanged' event names from an object's keys.

TypeScript & Web APIs2 min read

Conditional Types: Ternary Logic for Your Types

Conditional types are like a ternary operator for your type system, choosing a type based on a condition (`T extends U ? X : Y`). They're used with generics to make a function's return type depend on its input, avoiding cumbersome function overloads.