Created
May 4, 2021 18:24
-
-
Save mattdeboard/9877fc52a66638bc55a4e795e3403892 to your computer and use it in GitHub Desktop.
Sample type defs for typescript showing how to constrain function parameter combinations.
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
type Payload = Partial<{ [Key in AcceptableCombinations[1]]: number }>; | |
type EventObject = { | |
type: AcceptableCombinations[0]; | |
payload: Payload; | |
} | |
type AcceptableCombinations = | |
| [...[type: "a", key: "x"]] | |
| [...[type: "b", key: "y"]]; | |
function otherThing(...[type, key]: AcceptableCombinations) { | |
const payload: Payload = {[key]: key}; | |
const pp: Payload = {[key]: 7}; | |
const pq: Payload = {[key]: "x"}; | |
thing({ type, payload }); | |
} | |
function thing(obj: EventObject) { | |
console.log(JSON.stringify(obj, null, 2)); | |
} | |
otherThing("a", "x"); | |
otherThing('b', "y"); | |
// @ts-expect-error Invalid second argument given first argument | |
otherThing('a', "y"); | |
// @ts-expect-error Invalid second argument given first argument | |
otherThing("b", "x"); | |
// @ts-expect-error `y` is not assignable to type `never` - `"c"` is an invalid first argument. | |
otherThing("c", "y"); | |
// @ts-expect-error `{z: "z"}` is not assignable to type `{x: "x"}` | |
otherThing("a", "z"); | |
type Foo = { | |
x: number; | |
y: string; | |
} | |
type Bar = Pick<Foo, "x">; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment