Created
May 17, 2023 21:06
-
-
Save graffhyrum/e43843ef06174703dd725d584c9d9b91 to your computer and use it in GitHub Desktop.
Typescript generic to constrain to one key of a given interface/signature
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
| /** | |
| * A custom utility type to allow an object to be only one Type from the provided | |
| * Type. | |
| * @example | |
| * type OneOf = OneOfType<{userId:string, userEmail:string}>; | |
| * //allows {userId:string} || {userEmail:string}, but not both | |
| */ | |
| export type OneOfType<T> = ValueOf<OneOfByKey<T>>; | |
| type OneOfByKey<T> = {[key in keyof T]: OneOnly<T, key>}; | |
| type OneOnly<Obj, Key extends keyof Obj> = { | |
| [key in Exclude<keyof Obj, Key>]+?: undefined; | |
| } & Pick<Obj, Key>; | |
| type ValueOf<Obj extends object> = Obj[keyof Obj]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment