DEV Community

Cover image for React TypeScript - How To Set Types on Hooks (+cheat sheet)

React TypeScript - How To Set Types on Hooks (+cheat sheet)

Ibrahima Ndaw on August 04, 2020

TypeScript is a great language that allows type-checking your code in order to make it more robust and understandable. In this guide, I will lead ...
Collapse
 
kiwibennor profile image
Bennor McCarthy • Edited

Great advice. Really easy to do and a surprising number of people don't realise you can do this.

Minor nitpicky point, but you can get away with simplifying a couple of your examples, especially if you (and the other people reading your code) are comfortable with type inference:

const [counter, setCounter] = React.useState(0); // Infers number
// instead of
const [counter, setCounter] = React.useState<number>(0);

const myRef = React.useRef<HTMLElement>(null); // Infers HTMLElement | null
// instead of
const myRef = React.useRef<HTMLElement | null>(null);

 // No need for `| []`. Explicitly providing the generic argument means your `[]` argument to the function is treated as `[] as IArticle[]`.
const ArticleContext = React.createContext<IArticle[]>([]);
// instead of
const ArticleContext = React.createContext<IArticle[] | []>([]);
Enter fullscreen mode Exit fullscreen mode

Hovering the mouse over the variable name in VS Code is a great way to sanity check the types that have been inferred.

(You could argue that my first two examples are a possible source of confusion for people who are new to TypeScript, so feel free to completely ignore this advice.)

Collapse
 
abraganu profile image
Abraham Garcia Nunez • Edited

Pretty good stuff :), I will add that you need always set the return type of a function if you are working on strict mode (typescript). Another thing is that you can add read only to the reducers state

Collapse
 
bronxsystem profile image
bronxsystem • Edited

I needed this thank you good sir. Typescript new to my stack no more hacky code ~0~;;

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Glad it helps

Collapse
 
beraliv profile image
beraliv

Is there a way to apply types to useContext that prohibits using hook in case, the respective Provider won't be used with this component? It prevents forgetting the usage of providers.

Collapse
 
wobsoriano profile image
Robert

Good job.

Collapse
 
feelzz profile image
Peter Fields

You always provide good content. Simple and easy to understand. Great job!

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Wow! Thanks a lot

Collapse
 
dimaslz profile image
Dimas López

Good post, really useful!

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks for reading👍

Collapse
 
hurricaneman profile image
hurricaneman

Well written and very rewarding