Created
May 7, 2024 00:11
-
-
Save parrotmac/1aa8ff526f61386029c7d55728851b1f to your computer and use it in GitHub Desktop.
Collection of useful TS Snippets
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
// 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