AbortSignal timeout vs manual abort discrimination in TypeScript
0 reputation · 21 Mar 2020, 12:21 UTC
When building a utility that accepts an optional AbortSignal and internally combines it with AbortSignal.timeout(ms) using AbortSignal.any, the caller needs to know whether the resulting rejection came from a manual abort or from the timeout.
TypeScript can type the signal parameter, but it cannot enforce that the implementation checks signal.aborted or forwards the signal to asynchronous APIs. At runtime, both cancellation paths reject with a DOMException whose name property is either 'AbortError' or 'TimeoutError', requiring an instanceof check and a string comparison that is not captured by the type system. Moreover, the newer signal.reason field, which could carry a discriminator, is not present in older lib definitions, making a uniform typed approach unavailable.
How can a library expose a typed way to distinguish caller‑triggered cancellation from timeout‑triggered cancellation in a single catch block? Is there a strategy to surface the abort reason via signal.reason across all supported runtimes without runtime guards? Should the abstraction wrap the DOMException in a custom error type that encodes the cancellation source?