Skip to content

Instantly share code, notes, and snippets.

@tmatz
Created January 24, 2024 07:58
Show Gist options
  • Save tmatz/fb61de9c34f87c1f8bddfecfaa2675ae to your computer and use it in GitHub Desktop.
Save tmatz/fb61de9c34f87c1f8bddfecfaa2675ae to your computer and use it in GitHub Desktop.
Make union a type that allows destructuring assignment
/**
* Make union a type that allows destructuring assignment
* @example
* ```
* const props: { a: number } | { b: string } = ...
* const { a, b } = props as UnionDestructurable<typeof props>
* ```
*/
type UnionDestructurable<
Union,
UncommonKeys extends string = Exclude<
Union extends infer T ? keyof T : never,
keyof Union
>
> = Union &
(Union extends infer T
? { [K in UncommonKeys]?: K extends keyof T ? T[K] : never }
: never);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment