Skip to content

Instantly share code, notes, and snippets.

@ryangoree
Last active February 20, 2025 00:06
Show Gist options
  • Select an option

  • Save ryangoree/e70d5d78b821cbc94da33ef6fdcd4e4d to your computer and use it in GitHub Desktop.

Select an option

Save ryangoree/e70d5d78b821cbc94da33ef6fdcd4e4d to your computer and use it in GitHub Desktop.
Construct a type in which only a single member of `T` is valid at a time.
/**
* Construct a type in which only a single member of `T` is valid at a time.
*
* @example
* ```ts
* type U = OneOf<
* | {
* a: string;
* }
* | {
* b: string;
* c: number;
* }
* >;
* // {
* // a: string;
* // b?: undefined;
* // c?: undefined;
* // } | {
* // a?: undefined;
* // b: string;
* // c: number;
* // }
* ```
*/
type OneOf<T extends Record<PropertyKey, any>> = UnionKey<T> extends infer K extends
PropertyKey
? T extends T
? Eval<
T & {
[_ in Exclude<K, keyof T>]?: never;
}
>
: never
: never;
type Eval<T> = { [K in keyof T]: T[K] } & {};
type UnionKey<T> = T extends T ? keyof T : never;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment