Last active
June 24, 2022 15:55
-
-
Save iohcidnal/3a4912015930af8d3bd647ddaceec559 to your computer and use it in GitHub Desktop.
Create dynamic function signature
This file contains 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
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