Skip to content

Instantly share code, notes, and snippets.

@parrotmac
Created May 7, 2024 00:11
Show Gist options
  • Save parrotmac/1aa8ff526f61386029c7d55728851b1f to your computer and use it in GitHub Desktop.
Save parrotmac/1aa8ff526f61386029c7d55728851b1f to your computer and use it in GitHub Desktop.
Collection of useful TS Snippets
// Inclusive overlap of two types
type CommonProperties<T, U> = {
[K in keyof T & keyof U]: T[K] extends U[K] ? U[K] extends T[K] ? T[K] : never : never;
};
// Function signature that varies second arg type based on type of first
type Args<T> = T extends number ? Foo : T extends string ? Bar : never;
function dependentFunction<T extends number | string>(arg1: T, arg2: Args<T>): void {
if (typeof arg1 === "number") {
console.log("Number and Foo", arg1, (arg2 as Foo).fooProp);
} else if (typeof arg1 === "string") {
console.log("String and Bar", arg1, (arg2 as Bar).barProp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment