More in TypeScript & Web APIs — page 5

How do you cancel pending fetches using AbortController?
WHAT IT TESTS: Async cancellation and race-condition prevention in UI streams. ANSWER OUTLINE: Keep one AbortController, abort before each fetch, pass its signal, and swallow AbortError. RED FLAG: Forgetting prior abort or leaving rejections uncaught.
Create a generic fetchJson wrapper with typed response and error handling
WHAT IT TESTS: marrying TypeScript generics to fetch for typed responses and runtime error handling. ANSWER OUTLINE: generic T parameter, optional RequestInit, throw if !res.ok, return res.json() as Promise<T>. RED FLAG: using any or omitting the ok check.
How do you handle an API returning 200 for success and failure?
This tests TypeScript narrowing and runtime validation of ambiguous 200 responses. A strong answer uses a discriminated union, narrows with a type guard, and validates shape before branching. Red flag: casting the body with as and skipping runtime checks.

How do you include a JWT in a fetch request?
Tests knowledge of the fetch options object and Bearer scheme syntax. A strong answer sets headers: { Authorization: Bearer <token> } as the second argument and notes fetch does not auto-attach tokens. Red flag: omitting Bearer or hardcoding secrets.

Write a typed async fetchUser with error handling
Tests promise-based fetch plus TypeScript return-type contracts. A strong answer checks response.ok before response.json() and types the return as Promise<User>. A red flag is swallowing 4xx/5xx errors silently.

Write a createUser function that POSTs JSON via fetch
WHAT IT TESTS: precise fetch configuration for JSON POST requests. A strong answer names method POST, headers Content-Type application/json, and body JSON.stringify(data) with return typing. Red flag: passing the raw object as body or omitting headers.

How would you modify fetch to handle HTTP error statuses?
WHAT IT TESTS: awareness that fetch resolves on HTTP errors and needs manual status checking. ANSWER OUTLINE: verify response.ok in then and throw if false, then catch network failures separately.

Write a fetch call and log JSON from the Response
This tests async HTTP literacy and fetch's two-stage promise resolution. A strong answer awaits fetch, then awaits response.json(), logs result, and notes fetch does not throw on 4xx/5xx.

Implement inSequence(tasks) to execute promise-returning functions sequentially
Tests async/await control flow versus Promise.all parallelism. A strong answer uses a for-of loop with await inside an async function, accumulates results in order, and stops cleanly on rejection. Red flag: suggesting Promise.all or forEach with await.

How would you prevent search-as-you-type race conditions with AbortController?
WHAT IT TESTS: Canceling stale fetches to keep the UI consistent. ANSWER OUTLINE: Abort the previous request before each new keystroke, pass the fresh signal into fetch, and ignore the AbortError.

How do you type an async function return in TypeScript?
This tests if you know async functions always return Promise<T>. A great answer: annotate Promise<User>, return User from the body, and note TypeScript implicitly wraps it. A red flag is omitting Promise and typing the return as just User.

How do you fetch from three APIs using Promise.all versus allSettled?
WHAT IT TESTS: Promise concurrency and failure isolation. ANSWER OUTLINE: Promise.all parallelizes but rejects on first failure. allSettled returns every outcome with status, value, and reason. RED FLAG: Wrapping each call in try-catch to imitate allSettled.

How do you wrap a callback-based API into a Promise?
This tests Promise constructor mechanics and callback migration. A strong answer returns a new Promise, calls the legacy function, maps success to resolve and errors to reject.
Write a generic TypeScript handler for mixed form inputs?
Tests TypeScript DOM narrowing. Strong answer: union-type ChangeEvent, narrow target with instanceof or tag checks, branch on element.type to read .checked for checkboxes or .value otherwise. Red flag: casting to any or assuming all inputs use .value.

Implement IntersectionObserver in TypeScript for lazy-loading images
Tests precise DOM typing and observer lifecycle. A strong answer types the callback as receiving IntersectionObserverEntry[], narrows entry.target to HTMLImageElement, swaps data-src to src, and calls unobserve.

How would you use DocumentFragment to optimize adding 1,000 list items?
Tests DOM reflow/repaint costs and off-DOM batching. A strong answer: create a DocumentFragment, build the 1,000 nodes off-DOM, then append once to trigger a single reflow. Red flag: claiming it saves memory or confusing it with innerHTML batching.

Programmatically create and append a div in TypeScript
Tests TypeScript DOM typing and safe element creation. Strong answers name HTMLDivElement and Document, use createElement plus classList.add and textContent, then append. Red flag: innerHTML for text or avoiding specific types.
How do you type-safely check an LI click and read data-id?
Tests TypeScript narrowing with DOM event delegation. A strong answer uses closest to walk up from event.target, checks result with instanceof HTMLLIElement, then reads dataset.id. Red flag: casting event.target directly without handling nested child elements.
Strategies to type querySelector results as HTMLInputElement
Tests whether you know safe ways to narrow querySelector's Element or null to HTMLInputElement. A strong answer compares type assertions with generic querySelector calls, and insists on null checks. Red flag: asserting without runtime validation.

What is the click event's type and how to reference the button?
WHAT IT TESTS: DOM event inheritance and currentTarget versus target. ANSWER OUTLINE: Handler receives a MouseEvent. Use event.currentTarget for the attached button, since event.target may be a nested child.