TypeScript's type system is very powerful because it allows us to express types in terms of other types, including generics
I was looking at the implementation of the TS utilities & learned lots about how to implement generics, so I wanted to share my learnings
/thread 🧵👇🏾
1️⃣ Basic generics
Generic types are like implicit return funcs. They take 1+ params & return a new type
`Partial<>`, `Required<>` & `Readonly<>` take any obj type & return a new obj type w/ property modifiers
We can use them as an example for our own `Mutable<>` util!
🧵👇🏾
2️⃣ Generic constraints
Using `extends` we can restrict what types of params are allowed. It's kinda like providing types of our generic params
`Record<>` limits the `Keys` param to only `string`, `number` or `symbol` cuz JS objects only allow those types as keys
🧵👇🏾
3️⃣ Conditional generics
We can use a ternary operator to return the type based on a type condition
`NonNullable<>`, `Exclude<>` & `Extract<>` remove/select the types of the target param if the source param type matches
We can build `NonNullable<>` using `Exclude<>`!
🧵👇🏾
4️⃣ Generic references
Instead of restricting a param by predefined types, we can limit based on types of other params for relational validation! 🤯
`Pick<>` enforces that the strings listed are valid keys of the obj
And `Omit<>` is composed from `Pick<>` & `Exclude<>`
🧵👇🏾
We're really just scratching the surface on how TS generics work by rebuilding the utils, but it gives us insights into how we can build our own generic types
Check out my latest post w/ more explanations on how the code snippets work
🧵👇🏾
benmvp.com/blog/learn-typ…
📣 If you're interested in learning more about TypeScript I'm giving a workshop as a part of @cascadiajs on Nov 11 called "TypeScript for React Developers"
Workshop tickets are $50 off w/ purchase of conference ticket
🧵👇🏾
2021.cascadiajs.com/workshops/ts-r…
Back in July, I re-implemented 10 different lodash functions using the `.reduce()` method in order to help us better understand how `.reduce()` works
With `.reduce()` added to your tool belt, you'll be able to transform data with the best of them!
🧵👇🏾
benmvp.com/blog/learn-arr…
That's a wrap for this week! Feel free to subscribe to the BenMVP Newsletter for more of my posts on TypeScript/JavaScript, React, DivOps & other frontend goodies
Keep learning my friends. 🤓
benmvp.com/subscribe/?utm…
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.