Skip to content

Instantly share code, notes, and snippets.

@iohcidnal
Last active June 24, 2022 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iohcidnal/3a4912015930af8d3bd647ddaceec559 to your computer and use it in GitHub Desktop.
Save iohcidnal/3a4912015930af8d3bd647ddaceec559 to your computer and use it in GitHub Desktop.
Create dynamic function signature
type Person =
| {
firstName: string;
lastName: string;
isMarried: false;
}
| {
isMarried: true;
spouse: {
spouseFirstName: string;
spouseLastName: string;
};
};
export function createPerson<T extends Person["isMarried"]>(
isMarried: T,
...args: Extract<Person, { isMarried: T }> extends { spouse: infer S }
? [spouse: S]
: never
) {
console.log(args);
}
// Passing `true` to isMarried, requires you to also supply spouse info.
// This function call errors out because spouse object is missing.
createPerson(true)
// This function call works with spouse object
createPerson(true, { spouseFirstName: "John", spouseLastName: "Doe" });
// Passing `false` to isMarried does not require spouse object.
// This function call works without passing in the spouse object.
createPerson(false);
/** Closure style
export function createPerson<T extends Person["isMarried"]>(isMarried: T) {
return (
...args: Extract<Person, { isMarried: T }> extends { spouse: infer S }
? [spouse: S]
: never
) => {
console.log(args);
};
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment