Last active
February 20, 2025 00:06
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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