Matt Pocock on X: "🧵 Spotting Generics 🧵
Scared by TypeScript generics? The best way to get to grips with them is to understand how they're made.
Here's a guide to EVERY way you can instantiate a generic in TypeScript."
🧵 Spotting Generics 🧵
Scared by TypeScript generics? The best way to get to grips with them is to understand how they're made.
Here's a guide to EVERY way you can instantiate a generic in TypeScript.
🧵 Spotting Generics 🧵
Scared by TypeScript generics? The best way to get to grips with them is to understand how they're made.
Here's a guide to EVERY way you can instantiate a generic in TypeScript.
1⃣ Functions
You can add generic slots in the declaration of a function. They come just before the () brackets, and usually correspond to input arguments.
Here, myFunction will return the same type as you pass in - in this case a literal 20 type.
3⃣ Anonymous arrow functions
You can add generics to anonymous arrow functions, or functions that are returned from other functions.
Here, we create a generic 'func' from 'curriedFunctionCreator'.
4⃣ Classes
You can use generics in classes to infer arguments passed in from the constructor.
Here, we create a dynamic map inside a class based on the arguments the user passed in.
5⃣ Types and Interfaces
This is useful when you want your type/interface to be reusable or dynamic.
Here, we create a dynamic MyType, which creates a record of whatever we pass it.
ValueContainer creates { value: T }, where T is the generic.
6⃣ Functions declared in object types
You can add a generic inline in any type/interface/object definition and give it a generic slot - such as in obj.myFunc below.
7⃣ The infer keyword
Inside a conditional type check, you can instantiate a generic just for that condition by using the infer keyword.
This is useful when you want to grab generics directly from the slots of the type/interface you're checking against.