#Mapping discriminated unions?

1 messages · Page 1 of 1 (latest)

humble ore
#

I want to implement a type (handlerResult) that matches any element of a static array (responseDefs) representing the variants of a discriminated unions, but "processed" with a generic type (response):

The naive way I've tried does not produce a discriminated union, but instead merges values of the source object's properties like a construction like response< typeof responseDefs[number] > would do.

rocky quiverBOT
#
krulod#0

Preview:```ts
interface responseDef {
contentType: string
status: number
schema: object
}

const responseDefs = [
{contentType: 'application/json', status: 200, schema: {json_schema: true}},
{contentType: 'text/plain', status: 200, schema: {text_schema: true}},
...```

humble ore
#

Mapping discriminated unions?

sleek estuary
#

sounds like you need to distribute the union

rocky quiverBOT
#
that_guy977#0

Preview:```ts
...
type Response_<T extends ResponseDef> = T extends T ? {
status: T['status']
contentType: T['contentType']
content: { content_from: T['schema'] }
} : never

type Handler = () => (
typeof responseDefs extends infer T extends ResponseDef[]
? {
[I in keyof T]:
Response_<T[I]>
}[keyof T]
: never
)
...```

humble ore