Skip to content

Instantly share code, notes, and snippets.

@graffhyrum
Created May 17, 2023 21:06
Show Gist options
  • Select an option

  • Save graffhyrum/e43843ef06174703dd725d584c9d9b91 to your computer and use it in GitHub Desktop.

Select an option

Save graffhyrum/e43843ef06174703dd725d584c9d9b91 to your computer and use it in GitHub Desktop.
Typescript generic to constrain to one key of a given interface/signature
/**
* 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