Skip to content

Instantly share code, notes, and snippets.

@mattdeboard
Created May 4, 2021 18:24
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 mattdeboard/9877fc52a66638bc55a4e795e3403892 to your computer and use it in GitHub Desktop.
Save mattdeboard/9877fc52a66638bc55a4e795e3403892 to your computer and use it in GitHub Desktop.
Sample type defs for typescript showing how to constrain function parameter combinations.
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