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…

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Ben Ilegbodu 🏀👨🏾‍💻

Ben Ilegbodu 🏀👨🏾‍💻 Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @benmvp

13 Oct
What are some situations for when we can use the `useCallback()` & `useMemo()` Hooks in React components?

Well, one case where we need `useCallback()` is when we call a helper function w/in `useEffect()`, so we need "referential equality" to include it in deps

/thread 🧵👇🏾
I also use `useCallback()` by default when returning a function from a custom Hook cuz I dunno how that function will be used w/in host components

`useCallback()` gives a stable function reference similar to the updater func from `useState()` (the 2nd array element)

🧵👇🏾
The `useMemo()` Hook is similar to `useCallback()` except that it memoizes any value not just functions

So I use `useMemo()` in the same situations: when I have a derived object/array that's used in the deps of `useEffect()`

(I like to think of "memoization" as a cache)

🧵👇🏾
Read 8 tweets
22 Jul
The .reduce() method is maybe the most powerful, yet least understood array method. It basically allows us to transform an array into... nearly anything else

Let's re-implement 1️⃣0️⃣ lodash functions to learn more about how for examples on how .reduce works

/thread 👇🏾🧵
1️⃣ sum()

ℹ️ Computes the sum of the values in an array

The function is called a "reducer" & the 2nd param is our initial value

The 1st arg of the reducer is the "accumulator" (the value we're building up). The 2nd is the current array element in the iteration

/thread 👇🏾🧵
2️⃣ countBy()

ℹ️ Creates an object w/ keys that are the array elements and values that are their counts

Here we're turning an array into an object

(can't forget to return the object we're accumulating!)

/thread 👇🏾🧵
Read 13 tweets
19 May
Nope JSX doesn't have a built-in loop construct. Instead it offloads looping to JavaScript & just accepts an array of JSX elements for rendering lists

💡 So in React, to loop we gotta convert an array of data ➡️ array of JSX elements

Let's look at some ways how...

/thread 🧵👇🏾
Calling `.map` on the array is the most popular way to generate that array of JSX elements

And cuz `.map` returns a new array we can inline it directly in the JSX w/o using a var (also very common)

Putting the `.map` inline makes it *feel* like traditional loop templates

🧵👇🏾
Using a regular `for` loop (or `for-of`, `.forEach`, etc) requires a var that we gotta `.push` into

`for` is likely more familiar to JS newcomers but it means we cannot inline the code

...unless we wanna go rogue and put it in an IIFE 🤯 (anyone used one here before???)

🧵👇🏾
Read 7 tweets
23 Mar
Here is a quick React custom Hook that supports copying text to the system clipboard. It also returns a copied/failed status that can be reflected in the UI

(I remember the days when we could only do this w/ Flash 😭)

more details in the thread 🧵👇🏾
useCopyToClipboard returns a copy function that the UI calls when the user wants to copy the text (likely a button click). It updates the status based on the success/failure of writing to the clipboard

It uses useCallback to ensure a stable function reference

🧵👇🏾
It also uses useEffect to set a timeout that will reset the status after a specified amount of time. This basically makes the status fleeting, which is a typical user experience

🧵👇🏾
Read 6 tweets
26 Jan
Have y'all gotten that React warning about state updates after component unmount?

I get it mainly when running unit tests

Happens when:
- Make async request
- Component unmounts
- Response comes back
- Try to update state w/ new data

I've come up w/ 4️⃣ solutions

/thread 🧵👇🏾
Since vanilla JS Promises aren't cancellable the next best thing is to keep track of the mounted state & don't update state if the comp is unmounted

1️⃣ Variable to track mounted state

Quick & dirty, but only works in single useEffect w/ no deps

🧵👇🏾
2️⃣ Ref to track mounted state

All effects can check the ref regardless of if they have deps. Will have to duplicate in multiple components tho

🧵👇🏾
Read 8 tweets
14 Jan
If you're getting started with React in TypeScript one of the first things you'll wanna do is migrate from runtime prop-types over to static TS types

Typing a function component is the same as any function in TS

Typically props are typed with a TS `interface`

/thread 🧵👇🏾
The primitive prop types map over to their TS equivalents...

🧵👇🏾
Special types like React nodes, enums, class instances, and others...

🧵👇🏾
Read 7 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(