Newsletter
Sed ut perspiciatis unde.
Subscribe
|
// library code for non-generic discriminated unions |
|
export type ReplaceReturnType<F, R> = F extends (…args: infer Args) => any |
|
? (…args: Args) => R |
|
: never; |
|
|
|
export type TaggedUnionFactory<TUF, R> = { |
|
[K in keyof TUF]: ReplaceReturnType<TUF[K], R>; |
|
}; |
|
|
|
// for monomorphic types this just works well |
|
const _actionResult = { |
|
failure: (message: string) => ({ kind: “failure”, message } as const), |
|
value: (value: number) => ({ kind: “result”, value } as const), |
|
}; |
|
|
|
export type ActionResult = ReturnType< |
|
typeof _actionResult[keyof typeof _actionResult] |
|
>; |
|
|
|
export const actionResult: TaggedUnionFactory< |
|
typeof _actionResult, |
|
ActionResult |
|
> = _actionResult; |
|
|
|
// For generic types you have to type the usage sites but it’s still pretty good |
|
export const status = { |
|
loading: () => ({ kind: “loading” } as const), |
|
success: <V>(value: V) => ({ kind: “success”, value } as const), |
|
error: <E>(error: E) => ({ kind: “er |
Read More