typescript / expert
Snippet
Type-Safe Async Iterator Stream Transformation with Fault Tolerance
Async generators enable streaming asynchronous data. Wrapping yield operations inside a discriminated union StreamResult type ensures that processing failures during stream transformation do not abruptly unhandle exceptions or terminate the iterator stream, providing robust typed error recovery for reactive pipelines.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type StreamResult<T> =| { success: true; data: T }| { success: false; error: Error };async function* transformStream<TIn, TOut>(source: AsyncIterable<TIn>,transform: (item: TIn) => Promise<TOut>): AsyncGenerator<StreamResult<TOut>, void, unknown> {for await (const item of source) {try {const transformed = await transform(item);yield { success: true, data: transformed };} catch (err) {yield {success: false,error: err instanceof Error ? err : new Error(String(err))};}}}
Breakdown
1
type StreamResult<T> = | { success: true; data: T } | { success: false; error: Error };
Defines a discriminated union to represent either successfully transformed data or caught stream errors.
2
async function* transformStream<TIn, TOut>(
Declares an async generator returning AsyncGenerator typed with StreamResult<TOut> yields.
3
for await (const item of source)
Asynchronously iterates over items produced by the incoming AsyncIterable source.
4
yield { success: false, error: err instanceof Error ? err : new Error(String(err)) };
Catches runtime transformation errors and yields structured failure objects without crashing the loop.