Skip to content

typescript-cheatsheets/react

Repository files navigation

React+TypeScript Cheatsheets

Cheatsheets for experienced React developers getting started with TypeScript


react + ts logo

Web docs| Español| Português| Contribute!| Ask!

👋 This repo is maintained by@swyx,@eps1lonand@filiptammergard.We're so happy you want to try out TypeScript with React! If you see anything wrong or missing, pleasefile an issue!👍


All Contributors|Discord|Tweet

All React + TypeScript Cheatsheets

  • The Basic Cheatsheetis focused on helping React devs just start using TS in Reactapps
    • Focus on opinionated best practices, copy+pastable examples.
    • Explains some basic TS types usage and setup along the way.
    • Answers the most Frequently Asked Questions.
    • Does not cover generic type logic in detail. Instead we prefer to teach simple troubleshooting techniques for newbies.
    • The goal is to get effective with TS without learningtoo muchTS.
  • The Advanced Cheatsheethelps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+Reactlibraries.
    • It also has miscellaneous tips and tricks for pro users.
    • Advice for contributing to DefinitelyTyped.
    • The goal is to takefull advantageof TypeScript.
  • The Migrating Cheatsheethelps collate advice for incrementally migrating large codebases from JS or Flow,from people who have done it.
    • We do not try to convince people to switch, only to help people who have already decided.
    • ⚠️This is a new cheatsheet, all assistance is welcome.
  • The HOC Cheatsheet) specifically teaches people to write HOCs with examples.
    • Familiarity withGenericsis necessary.
    • ⚠️This is the newest cheatsheet, all assistance is welcome.

Basic Cheatsheet

Basic Cheatsheet Table of Contents

Expand Table of Contents

Section 1: Setup

Prerequisites

You can use this cheatsheet for reference at any skill level, but basic understanding of React and TypeScript is assumed. Here is a list of prerequisites:

In the cheatsheet we assume you are using the latest versions of React and TypeScript.

React and TypeScript starter kits

React has documentation forhow to start a new React projectwith some of the most popular frameworks. Here's how to start them with TypeScript:

  • Next.js:npx create-next-app@latest --ts
  • Remix:npx create-remix@latest
  • Gatsby:npm init gatsby --ts
  • Expo:npx create-expo-app -t with-typescript

Try React and TypeScript online

There are some tools that let you run React and TypeScript online, which can be helpful for debugging or making sharable reproductions.

Section 2: Getting Started

Function Components

These can be written as normal functions that take apropsargument and return a JSX element.

// Declaring type of props - see "Typing Component Props" for more examples
typeAppProps={
message:string;
};/* use `interface` if exporting so that consumers can extend */

// Easiest way to declare a Function Component; return type is inferred.
constApp=({message}:AppProps)=><div>{message}</div>;

// You can choose to annotate the return type so an error is raised if you accidentally return some other type
constApp=({message}:AppProps):React.JSX.Element=><div>{message}</div>;

// You can also inline the type declaration; eliminates naming the prop types, but looks repetitive
constApp=({message}:{message:string})=><div>{message}</div>;

// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.
// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.
constApp:React.FunctionComponent<{message:string}>=({message})=>(
<div>{message}</div>
);
// or
constApp:React.FC<AppProps>=({message})=><div>{message}</div>;

Tip: You might usePaul Shen's VS Code Extensionto automate the type destructure declaration (incl akeyboard shortcut).

Why isReact.FCnot needed? What aboutReact.FunctionComponent/React.VoidFunctionComponent?

You may see this in many React+TypeScript codebases:

constApp:React.FunctionComponent<{message:string}>=({message})=>(
<div>{message}</div>
);

However, the general consensus today is thatReact.FunctionComponent(or the shorthandReact.FC) is not needed. If you're still using React 17 or TypeScript lower than 5.1, it is evendiscouraged.This is a nuanced opinion of course, but if you agree and want to removeReact.FCfrom your codebase, you can usethis jscodeshift codemod.

Some differences from the "normal function" version:

  • React.FunctionComponentis explicit about the return type, while the normal function version is implicit (or else needs additional annotation).

  • It provides typechecking and autocomplete for static properties likedisplayName,propTypes,anddefaultProps.

    • Note that there are some known issues usingdefaultPropswithReact.FunctionComponent.Seethis issue for details.We maintain a separatedefaultPropssection you can also look up.
  • Before theReact 18 type updates,React.FunctionComponentprovided an implicit definition ofchildren(see below), which was heavily debated and is one of the reasonsReact.FCwas removed from the Create React App TypeScript template.

// before React 18 types
constTitle:React.FunctionComponent<{title:string}>=({
children,
title,
})=><divtitle={title}>{children}</div>;
(Deprecated)UsingReact.VoidFunctionComponentorReact.VFCinstead

In@types/react 16.9.48,theReact.VoidFunctionComponentorReact.VFCtype was added for typingchildrenexplicitly. However, please be aware thatReact.VFCandReact.VoidFunctionComponentwere deprecated in React 18 (DefinitelyTyped/DefinitelyTyped#59882), so this interim solution is no longer necessary or recommended in React 18+.

Please use regular function components orReact.FCinstead.

typeProps={foo:string};

// OK now, in future, error
constFunctionComponent:React.FunctionComponent<Props>=({
foo,
children,
}:Props)=>{
return(
<div>
{foo}{children}
</div>
);// OK
};

// Error now, in future, deprecated
constVoidFunctionComponent:React.VoidFunctionComponent<Props>=({
foo,
children,
})=>{
return(
<div>
{foo}
{children}
</div>
);
};
  • In the future,it may automatically mark props asreadonly,though that's a moot point if the props object is destructured in the parameter list.

In most cases it makes very little difference which syntax is used, but you may prefer the more explicit nature ofReact.FunctionComponent.

Hooks

Hooks aresupported in@types/reactfrom v16.8 up.

useState

Type inference works very well for simple values:

const[state,setState]=useState(false);
// `state` is inferred to be a boolean
// `setState` only takes booleans

See also theUsing Inferred Typessection if you need to use a complex type that you've relied on inference for.

However, many hooks are initialized with null-ish default values, and you may wonder how to provide types. Explicitly declare the type, and use a union type:

const[user,setUser]=useState<User|null>(null);

// later...
setUser(newUser);

You can also use type assertions if a state is initialized soon after setup and always has a value after:

const[user,setUser]=useState<User>({}asUser);

// later...
setUser(newUser);

This temporarily "lies" to the TypeScript compiler that{}is of typeUser.You should follow up by setting theuserstate — if you don't, the rest of your code may rely on the fact thatuseris of typeUserand that may lead to runtime errors.

useCallback

You can type theuseCallbackjust like any other function.

constmemoizedCallback=useCallback(
(param1:string,param2:number)=>{
console.log(param1,param2)
return{ok:true}
},
[...],
);
/**
* VSCode will show the following type:
* const memoizedCallback:
* (param1: string, param2: number) => { ok: boolean }
*/

Note that for React < 18, the function signature ofuseCallbacktyped arguments asany[]by default:

functionuseCallback<Textends(...args:any[])=>any>(
callback:T,
deps:DependencyList
):T;

In React >= 18, the function signature ofuseCallbackchanged to the following:

functionuseCallback<TextendsFunction>(callback:T,deps:DependencyList):T;

Therefore, the following code will yield "Parameter 'e' implicitly has an 'any' type."error in React >= 18, but not <17.

// @ts-expect-error Parameter 'e' implicitly has 'any' type.
useCallback((e)=>{},[]);
// Explicit 'any' type.
useCallback((e:any)=>{},[]);

useReducer

You can useDiscriminated Unionsfor reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.

import{useReducer}from"react";

constinitialState={count:0};

typeACTIONTYPE=
|{type:"increment";payload:number}
|{type:"decrement";payload:string};

functionreducer(state:typeofinitialState,action:ACTIONTYPE){
switch(action.type){
case"increment":
return{count:state.count+action.payload};
case"decrement":
return{count:state.count-Number(action.payload)};
default:
thrownewError();
}
}

functionCounter(){
const[state,dispatch]=useReducer(reducer,initialState);
return(
<>
Count:{state.count}
<buttononClick={()=>dispatch({type:"decrement",payload:"5"})}>
-
</button>
<buttononClick={()=>dispatch({type:"increment",payload:5})}>
+
</button>
</>
);
}

View in the TypeScript Playground

Usage withReducerfromredux

In case you use thereduxlibrary to write reducer function, It provides a convenient helper of the formatReducer<State, Action>which takes care of the return type for you.

So the above reducer example becomes:

import{Reducer}from'redux';

exportfunctionreducer:Reducer<AppState,Action>(){}

useEffect / useLayoutEffect

Both ofuseEffectanduseLayoutEffectare used for performingside effectsand return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When usinguseEffect,take care not to return anything other than a function orundefined,otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:

functionDelayedEffect(props:{timerMs:number}){
const{timerMs}=props;

useEffect(
()=>
setTimeout(()=>{
/* do stuff */
},timerMs),
[timerMs]
);
// bad example! setTimeout implicitly returns a number
// because the arrow function body isn't wrapped in curly braces
returnnull;
}
Solution to the above example
functionDelayedEffect(props:{timerMs:number}){
const{timerMs}=props;

useEffect(()=>{
setTimeout(()=>{
/* do stuff */
},timerMs);
},[timerMs]);
// better; use the void keyword to make sure you return undefined
returnnull;
}

useRef

In TypeScript,useRefreturns a reference that is eitherread-onlyormutable,depends on whether your type argument fully covers the initial value or not. Choose one that suits your use case.

Option 1: DOM element ref

To access a DOM element:provide only the element type as argument, and usenullas initial value. In this case, the returned reference will have a read-only.currentthat is managed by React. TypeScript expects you to give this ref to an element'srefprop:

functionFoo(){
// - If possible, prefer as specific as possible. For example, HTMLDivElement
// is better than HTMLElement and way better than Element.
// - Technical-wise, this returns RefObject<HTMLDivElement>
constdivRef=useRef<HTMLDivElement>(null);

useEffect(()=>{
// Note that ref.current may be null. This is expected, because you may
// conditionally render the ref-ed element, or you may forget to assign it
if(!divRef.current)throwError("divRef is not assigned");

// Now divRef.current is sure to be HTMLDivElement
doSomethingWith(divRef.current);
});

// Give the ref to an element so React can manage it for you
return<divref={divRef}>etc</div>;
}

If you are sure thatdivRef.currentwill never be null, it is also possible to use the non-null assertion operator!:

constdivRef=useRef<HTMLDivElement>(null!);
// Later... No need to check if it is null
doSomethingWith(divRef.current);

Note that you are opting out of type safety here - you will have a runtime error if you forget to assign the ref to an element in the render, or if the ref-ed element is conditionally rendered.

Tip: Choosing whichHTMLElementto use

Refs demand specificity - it is not enough to just specify any oldHTMLElement.If you don't know the name of the element type you need, you can checklib.dom.tsor make an intentional type error and let the language service tell you:

image

Option 2: Mutable value ref

To have a mutable value:provide the type you want, and make sure the initial value fully belongs to that type:

functionFoo(){
// Technical-wise, this returns MutableRefObject<number | null>
constintervalRef=useRef<number|null>(null);

// You manage the ref yourself (that's why it's called MutableRefObject!)
useEffect(()=>{
intervalRef.current=setInterval(...);
return()=>clearInterval(intervalRef.current);
},[]);

// The ref is not passed to any element's "ref" prop
return<buttononClick={/* clearInterval the ref */}>Cancel timer</button>;
}
See also

useImperativeHandle

Based on thisStackoverflow answer:

// Countdown.tsx

// Define the handle types which will be passed to the forwardRef
exporttypeCountdownHandle={
start:()=>void;
};

typeCountdownProps={};

constCountdown=forwardRef<CountdownHandle,CountdownProps>((props,ref)=>{
useImperativeHandle(ref,()=>({
// start() has type inference here
start(){
alert("Start");
},
}));

return<div>Countdown</div>;
});
// The component uses the Countdown component

importCountdown,{CountdownHandle}from"./Countdown.tsx";

functionApp(){
constcountdownEl=useRef<CountdownHandle>(null);

useEffect(()=>{
if(countdownEl.current){
// start() has type inference here as well
countdownEl.current.start();
}
},[]);

return<Countdownref={countdownEl}/>;
}
See also:

Custom Hooks

If you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScript will infer a union type (when you actually want different types in each position of the array). Instead, useTS 3.4 const assertions:

import{useState}from"react";

exportfunctionuseLoading(){
const[isLoading,setState]=useState(false);
constload=(aPromise:Promise<any>)=>{
setState(true);
returnaPromise.finally(()=>setState(false));
};
return[isLoading,load]asconst;// infers [boolean, typeof load] instead of (boolean | typeof load)[]
}

View in the TypeScript Playground

This way, when you destructure you actually get the right types based on destructure position.

Alternative: Asserting a tuple return type

If you arehaving trouble with const assertions,you can also assert or define the function return types:

import{useState}from"react";

exportfunctionuseLoading(){
const[isLoading,setState]=useState(false);
constload=(aPromise:Promise<any>)=>{
setState(true);
returnaPromise.finally(()=>setState(false));
};
return[isLoading,load]as[
boolean,
(aPromise:Promise<any>)=>Promise<any>
];
}

A helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:

functiontuplify<Textendsany[]>(...elements:T){
returnelements;
}

functionuseArray(){
constnumberValue=useRef(3).current;
constfunctionValue=useRef(()=>{}).current;
return[numberValue,functionValue];// type is (number | (() => void))[]
}

functionuseTuple(){
constnumberValue=useRef(3).current;
constfunctionValue=useRef(()=>{}).current;
returntuplify(numberValue,functionValue);// type is [number, () => void]
}

Note that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however.

More Hooks + TypeScript reading:

If you are writing a React Hooks library, don't forget that you should also expose your types for users to use.

Example React Hooks + TypeScript Libraries:

Something to add? File an issue.

Class Components

Within TypeScript,React.Componentis a generic type (akaReact.Component<PropType, StateType>), so you want to provide it with (optional) prop and state type parameters:

typeMyProps={
// using `interface` is also ok
message:string;
};
typeMyState={
count:number;// like this
};
classAppextendsReact.Component<MyProps,MyState>{
state:MyState={
// optional second annotation for better type inference
count:0,
};
render(){
return(
<div>
{this.props.message}{this.state.count}
</div>
);
}
}

View in the TypeScript Playground

Don't forget that you can export/import/extend these types/interfaces for reuse.

Why annotatestatetwice?

It isn't strictly necessary to annotate thestateclass property, but it allows better type inference when accessingthis.stateand also initializing the state.

This is because they work in two different ways, the 2nd generic type parameter will allowthis.setState()to work correctly, because that method comes from the base class, but initializingstateinside the component overrides the base implementation so you have to make sure that you tell the compiler that you're not actually doing anything different.

See commentary by @ferdaber here.

No need forreadonly

You often see sample code includereadonlyto mark props and state immutable:

typeMyProps={
readonlymessage:string;
};
typeMyState={
readonlycount:number;
};

This is not necessary asReact.Component<P,S>already marks them as immutable. (See PR and discussion!)

Class Methods:Do it like normal, but just remember any arguments for your functions also need to be typed:

classAppextendsReact.Component<{message:string},{count:number}>{
state={count:0};
render(){
return(
<divonClick={()=>this.increment(1)}>
{this.props.message}{this.state.count}
</div>
);
}
increment=(amt:number)=>{
// like this
this.setState((state)=>({
count:state.count+amt,
}));
};
}

View in the TypeScript Playground

Class Properties:If you need to declare class properties for later use, just declare it likestate,but without assignment:

classAppextendsReact.Component<{
message:string;
}>{
pointer:number;// like this
componentDidMount(){
this.pointer=3;
}
render(){
return(
<div>
{this.props.message}and{this.pointer}
</div>
);
}
}

View in the TypeScript Playground

Something to add? File an issue.

Typing getDerivedStateFromProps

Before you start usinggetDerivedStateFromProps,please go through thedocumentationandYou Probably Don't Need Derived State.Derived State can be implemented using hooks which can also help set up memoization.

Here are a few ways in which you can annotategetDerivedStateFromProps

  1. If you have explicitly typed your derived state and want to make sure that the return value fromgetDerivedStateFromPropsconforms to it.
classCompextendsReact.Component<Props,State>{
staticgetDerivedStateFromProps(
props:Props,
state:State
):Partial<State>|null{
//
}
}
  1. When you want the function's return value to determine your state.
classCompextendsReact.Component<
Props,
ReturnType<typeofComp["getDerivedStateFromProps"]>
>{
staticgetDerivedStateFromProps(props:Props){}
}
  1. When you want derived state with other state fields and memoization
typeCustomValue=any;
interfaceProps{
propA:CustomValue;
}
interfaceDefinedState{
otherStateField:string;
}
typeState=DefinedState&ReturnType<typeoftransformPropsToState>;
functiontransformPropsToState(props:Props){
return{
savedPropA:props.propA,// save for memoization
derivedState:props.propA,
};
}
classCompextendsReact.PureComponent<Props,State>{
constructor(props:Props){
super(props);
this.state={
otherStateField:"123",
...transformPropsToState(props),
};
}
staticgetDerivedStateFromProps(props:Props,state:State){
if(isEqual(props.propA,state.savedPropA))returnnull;
returntransformPropsToState(props);
}
}

View in the TypeScript Playground

You May Not NeeddefaultProps

As perthis tweet,defaultProps will eventually be deprecated. You can check the discussions here:

The consensus is to use object default values.

Function Components:

typeGreetProps={age?:number};

constGreet=({age=21}:GreetProps)=>// etc

Class Components:

typeGreetProps={
age?:number;
};

classGreetextendsReact.Component<GreetProps>{
render(){
const{age=21}=this.props;
/*...*/
}
}

letel=<Greetage={3}/>;

TypingdefaultProps

Type inference improved greatly fordefaultPropsinTypeScript 3.0+,althoughsome edge cases are still problematic.

Function Components

// using typeof as a shortcut; note that it hoists!
// you can also declare the type of DefaultProps if you choose
// e.g. https://github /typescript-cheatsheets/react/issues/415#issuecomment-841223219
typeGreetProps={age:number}&typeofdefaultProps;

constdefaultProps={
age:21,
};

constGreet=(props:GreetProps)=>{
// etc
};
Greet.defaultProps=defaultProps;

See this in TS Playground

ForClass components,there area couple ways to do it(including using thePickutility type) but the recommendation is to "reverse" the props definition:

typeGreetProps=typeofGreet.defaultProps&{
age:number;
};

classGreetextendsReact.Component<GreetProps>{
staticdefaultProps={
age:21,
};
/*...*/
}

// Type-checks! No type assertions needed!
letel=<Greetage={3}/>;
React.JSX.LibraryManagedAttributesnuance for library authors

The above implementations work fine for App creators, but sometimes you want to be able to exportGreetPropsso that others can consume it. The problem here is that the wayGreetPropsis defined,ageis a required prop when it isn't because ofdefaultProps.

The insight to have here is thatGreetPropsis theinternalcontract for your component, not theexternal,consumer facing contract.You could create a separate type specifically for export, or you could make use of theReact.JSX.LibraryManagedAttributesutility:

// internal contract, should not be exported out
typeGreetProps={
age:number;
};

classGreetextendsComponent<GreetProps>{
staticdefaultProps={age:21};
}

// external contract
exporttypeApparentGreetProps=React.JSX.LibraryManagedAttributes<
typeofGreet,
GreetProps
>;

This will work properly, although hovering overApparentGreetPropsmay be a little intimidating. You can reduce this boilerplate with theComponentPropsutility detailed below.

Consuming Props of a Component with defaultProps

A component withdefaultPropsmay seem to have some required props that actually aren't.

Problem Statement

Here's what you want to do:

interfaceIProps{
name:string;
}
constdefaultProps={
age:25,
};
constGreetComponent=({name,age}:IProps&typeofdefaultProps)=>(
<div>{`Hello, my name is${name},${age}`}</div>
);
GreetComponent.defaultProps=defaultProps;

constTestComponent=(props:React.ComponentProps<typeofGreetComponent>)=>{
return<h1/>;
};

// Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
constel=<TestComponentname="foo"/>;
Solution

Define a utility that appliesReact.JSX.LibraryManagedAttributes:

typeComponentProps<T>=Textends
|React.ComponentType<inferP>
|React.Component<inferP>
?React.JSX.LibraryManagedAttributes<T,P>
:never;

constTestComponent=(props:ComponentProps<typeofGreetComponent>)=>{
return<h1/>;
};

// No error
constel=<TestComponentname="foo"/>;

See this in TS Playground

Misc Discussions and Knowledge

Why doesReact.FCbreakdefaultProps?

You can check the discussions here:

This is just the current state and may be fixed in future.

TypeScript 2.9 and earlier

For TypeScript 2.9 and earlier, there's more than one way to do it, but this is the best advice we've yet seen:

typeProps=Required<typeofMyComponent.defaultProps>&{
/* additional props here */
};

exportclassMyComponentextendsReact.Component<Props>{
staticdefaultProps={
foo:"foo",
};
}

Our former recommendation used thePartial typefeature in TypeScript, which means that the current interface will fulfill a partial version on the wrapped interface. In that way we can extend defaultProps without any changes in the types!

interfaceIMyComponentProps{
firstProp?:string;
secondProp:IPerson[];
}

exportclassMyComponentextendsReact.Component<IMyComponentProps>{
publicstaticdefaultProps:Partial<IMyComponentProps>={
firstProp:"default",
};
}

The problem with this approach is it causes complex issues with the type inference working withReact.JSX.LibraryManagedAttributes.Basically it causes the compiler to think that when creating a JSX expression with that component, that all of its props are optional.

See commentary by @ferdaber hereandhere.

Something to add? File an issue.

Typing Component Props

This is intended as a basic orientation and reference for React developers familiarizing with TypeScript.

Basic Prop Types Examples

A list of TypeScript types you will likely use in a React+TypeScript app:

typeAppProps={
message:string;
count:number;
disabled:boolean;
/** array of a type! */
names:string[];
/** string literals to specify exact string values, with a union type to join them together */
status:"waiting"|"success";
/** an object with known properties (but could have more at runtime) */
obj:{
id:string;
title:string;
};
/** array of objects! (common) */
objArr:{
id:string;
title:string;
}[];
/** any non-primitive value - can't access any properties (NOT COMMON but useful as placeholder) */
obj2:object;
/** an interface with no required properties - (NOT COMMON, except for things like `React.Component<{}, State>`) */
obj3:{};
/** a dict object with any number of properties of the same type */
dict1:{
[key:string]:MyTypeHere;
};
dict2:Record<string,MyTypeHere>;// equivalent to dict1
/** function that doesn't take or return anything (VERY COMMON) */
onClick:()=>void;
/** function with named prop (VERY COMMON) */
onChange:(id:number)=>void;
/** function type syntax that takes an event (VERY COMMON) */
onChange:(event:React.ChangeEvent<HTMLInputElement>)=>void;
/** alternative function type syntax that takes an event (VERY COMMON) */
onClick(event:React.MouseEvent<HTMLButtonElement>):void;
/** any function as long as you don't invoke it (not recommended) */
onSomething:Function;
/** an optional prop (VERY COMMON!) */
optional?:OptionalType;
/** when passing down the state setter function returned by `useState` to a child component. `number` is an example, swap out with whatever the type of your state */
setState:React.Dispatch<React.SetStateAction<number>>;
};
objectas the non-primitive type

objectis a common source of misunderstanding in TypeScript. It does not mean "any object" but rather "any non-primitive type", which means it represents anything that is notnumber,bigint,string,boolean,symbol,nullorundefined.

Typing "any non-primitive value" is most likely not something that you should do much in React, which means you will probably not useobjectmuch.

Empty interface,{}andObject

An empty interface,{}andObjectall represent "any non-nullish value" —not "an empty object" as you might think.Using these types is a common source of misunderstanding and is not recommended.

interfaceAnyNonNullishValue{}// equivalent to `type AnyNonNullishValue = {}` or `type AnyNonNullishValue = Object`

letvalue:AnyNonNullishValue;

// these are all fine, but might not be expected
value=1;
value="foo";
value=()=>alert("foo");
value={};
value={foo:"bar"};

// these are errors
value=undefined;
value=null;

Useful React Prop Type Examples

Relevant for components that accept other React components as props.

exportdeclareinterfaceAppProps{
children?:React.ReactNode;// best, accepts everything React can render
childrenElement:React.JSX.Element;// A single React element
style?:React.CSSProperties;// to pass through style props
onChange?:React.FormEventHandler<HTMLInputElement>;// form events! the generic parameter is the type of event.target
// more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring
props:Props&React.ComponentPropsWithoutRef<"button">;// to impersonate all the props of a button element and explicitly not forwarding its ref
props2:Props&React.ComponentPropsWithRef<MyButtonWithForwardRef>;// to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref
}
SmallReact.ReactNodeedge case before React 18

Before theReact 18 type updates,this code typechecked but had a runtime error:

typeProps={
children?:React.ReactNode;
};

functionComp({children}:Props){
return<div>{children}</div>;
}
functionApp(){
// Before React 18: Runtime error "Objects are not valid as a React child"
// After React 18: Typecheck error "Type '{}' is not assignable to type 'ReactNode'"
return<Comp>{{}}</Comp>;
}

This is becauseReactNodeincludesReactFragmentwhich allowed type{}before React 18.

Thanks @pomle for raising this.

React.JSX.Element vs React.ReactNode?

Quote@ferdaber:A more technical explanation is that a valid React node is not the same thing as what is returned byReact.createElement.Regardless of what a component ends up rendering,React.createElementalways returns an object, which is theReact.JSX.Elementinterface, butReact.ReactNodeis the set of all possible return values of a component.

  • React.JSX.Element-> Return value ofReact.createElement
  • React.ReactNode-> Return value of a component

More discussion: Where ReactNode does not overlap with React.JSX.Element

Something to add? File an issue.

Types or Interfaces?

You can use either Types or Interfaces to type Props and State, so naturally the question arises - which do you use?

TL;DR

Use Interface until You Need Type -orta.

More Advice

Here's a helpful rule of thumb:

  • always useinterfacefor public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them viadeclaration mergingif some definitions are missing.

  • consider usingtypefor your React Component Props and State, for consistency and because it is more constrained.

You can read more about the reasoning behind this rule of thumb inInterface vs Type alias in TypeScript 2.7.

The TypeScript Handbook now also includes guidance onDifferences Between Type Aliases and Interfaces.

Note: At scale, there are performance reasons to prefer interfaces (see official Microsoft notes on this) buttake this with a grain of salt

Types are useful for union types (e.g.type MyType = TypeA | TypeB) whereas Interfaces are better for declaring dictionary shapes and thenimplementingorextendingthem.

Useful table for Types vs Interfaces

It's a nuanced topic, don't get too hung up on it. Here's a handy table:

Aspect Type Interface
Can describe functions
Can describe constructors
Can describe tuples
Interfaces can extend it ⚠️
Classes can extend it 🚫
Classes can implement it (implements) ⚠️
Can intersect another one of its kind ⚠️
Can create a union with another one of its kind 🚫
Can be used to create mapped types 🚫
Can be mapped over with mapped types
Expands in error messages and logs 🚫
Can be augmented 🚫
Can be recursive ⚠️

⚠️In some cases

(source:Karol Majewski)

Something to add? File an issue.

getDerivedStateFromProps

Before you start usinggetDerivedStateFromProps,please go through thedocumentationandYou Probably Don't Need Derived State.Derived State can be easily achieved using hooks which can also help set up memoization easily.

Here are a few ways in which you can annotategetDerivedStateFromProps

  1. If you have explicitly typed your derived state and want to make sure that the return value fromgetDerivedStateFromPropsconforms to it.
classCompextendsReact.Component<Props,State>{
staticgetDerivedStateFromProps(
props:Props,
state:State
):Partial<State>|null{
//
}
}
  1. When you want the function's return value to determine your state.
classCompextendsReact.Component<
Props,
ReturnType<typeofComp["getDerivedStateFromProps"]>
>{
staticgetDerivedStateFromProps(props:Props){}
}
  1. When you want derived state with other state fields and memoization
typeCustomValue=any;
interfaceProps{
propA:CustomValue;
}
interfaceDefinedState{
otherStateField:string;
}
typeState=DefinedState&ReturnType<typeoftransformPropsToState>;
functiontransformPropsToState(props:Props){
return{
savedPropA:props.propA,// save for memoization
derivedState:props.propA,
};
}
classCompextendsReact.PureComponent<Props,State>{
constructor(props:Props){
super(props);
this.state={
otherStateField:"123",
...transformPropsToState(props),
};
}
staticgetDerivedStateFromProps(props:Props,state:State){
if(isEqual(props.propA,state.savedPropA))returnnull;
returntransformPropsToState(props);
}
}

View in the TypeScript Playground

Forms and Events

If performance is not an issue (and it usually isn't!), inlining handlers is easiest as you can just usetype inference and contextual typing:

constel=(
<button
onClick={(event)=>{
/* event will be correctly typed automatically! */
}}
/>
);

But if you need to define your event handler separately, IDE tooling really comes in handy here, as the @type definitions come with a wealth of typing. Type what you are looking for and usually the autocomplete will help you out. Here is what it looks like for anonChangefor a form event:

typeState={
text:string;
};
classAppextendsReact.Component<Props,State>{
state={
text:"",
};

// typing on RIGHT hand side of =
onChange=(e:React.FormEvent<HTMLInputElement>):void=>{
this.setState({text:e.currentTarget.value});
};
render(){
return(
<div>
<inputtype="text"value={this.state.text}onChange={this.onChange}/>
</div>
);
}
}

View in the TypeScript Playground

Instead of typing the arguments and return values withReact.FormEvent<>andvoid,you may alternatively apply types to the event handler itself (contributed by @TomasHubelbauer):

// typing on LEFT hand side of =
onChange:React.ChangeEventHandler<HTMLInputElement>=(e)=>{
this.setState({text:e.currentTarget.value})
}
Why two ways to do the same thing?

The first method uses an inferred method signature(e: React.FormEvent<HTMLInputElement>): voidand the second method enforces a type of the delegate provided by@types/react.SoReact.ChangeEventHandler<>is simply a "blessed" typing by@types/react,whereas you can think of the inferred method as more...artisanally hand-rolled.Either way it's a good pattern to know.See our Github PR for more.

Typing onSubmit, with Uncontrolled components in a Form

If you don't quite care about the type of the event, you can just useReact.SyntheticEvent.If your target form has custom named inputs that you'd like to access, you can use a type assertion:

<form
ref={formRef}
onSubmit={(e:React.SyntheticEvent)=>{
e.preventDefault();
consttarget=e.targetastypeofe.target&{
email:{value:string};
password:{value:string};
};
constemail=target.email.value;// typechecks!
constpassword=target.password.value;// typechecks!
// etc...
}}
>
<div>
<label>
Email:
<inputtype="email"name="email"/>
</label>
</div>
<div>
<label>
Password:
<inputtype="password"name="password"/>
</label>
</div>
<div>
<inputtype="submit"value="Log in"/>
</div>
</form>

View in the TypeScript Playground

Of course, if you're making any sort of significant form,you should use FormikorReact Hook Form,which are written in TypeScript.

List of event types
Event Type Description
AnimationEvent CSS Animations.
ChangeEvent Changing the value of<input>,<select>and<textarea>element.
ClipboardEvent Using copy, paste and cut events.
CompositionEvent Events that occur due to the user indirectly entering text (e.g. depending on Browser and PC setup, a popup window may appear with additional characters if you e.g. want to type Japanese on a US Keyboard)
DragEvent Drag and drop interaction with a pointer device (e.g. mouse).
FocusEvent Event that occurs when elements gets or loses focus.
FormEvent Event that occurs whenever a form or form element gets/loses focus, a form element value is changed or the form is submitted.
InvalidEvent Fired when validity restrictions of an input fails (e.g<input type= "number" max= "10" >and someone would insert number 20).
KeyboardEvent User interaction with the keyboard. Each event describes a single key interaction.
MouseEvent Events that occur due to the user interacting with a pointing device (e.g. mouse)
PointerEvent Events that occur due to user interaction with a variety pointing of devices such as mouse, pen/stylus, a touchscreen and which also supports multi-touch. Unless you develop for older browsers (IE10 or Safari 12), pointer events are recommended. Extends UIEvent.
TouchEvent Events that occur due to the user interacting with a touch device. Extends UIEvent.
TransitionEvent CSS Transition. Not fully browser supported. Extends UIEvent
UIEvent Base Event for Mouse, Touch and Pointer events.
WheelEvent Scrolling on a mouse wheel or similar input device. (Note:wheelevent should not be confused with thescrollevent)
SyntheticEvent The base event for all above events. Should be used when unsure about event type
What aboutInputEvent?

You've probably noticed that there is noInputEvent.This is because it is not supported by Typescript as the event itself has no fully browser support and may behave differently in different browsers. You can useKeyboardEventinstead.

Sources:

Context

Basic example

Here's a basic example of creating a context containing the active theme.

import{createContext}from"react";

typeThemeContextType="light"|"dark";

constThemeContext=createContext<ThemeContextType>("light");

Wrap the components that need the context with a context provider:

import{useState}from"react";

constApp=()=>{
const[theme,setTheme]=useState<ThemeContextType>("light");

return(
<ThemeContext.Providervalue={theme}>
<MyComponent/>
</ThemeContext.Provider>
);
};

CalluseContextto read and subscribe to the context.

import{useContext}from"react";

constMyComponent=()=>{
consttheme=useContext(ThemeContext);

return<p>The current theme is{theme}.</p>;
};

Without default context value

If you don't have any meaningful default value, specifynull:

import{createContext}from"react";

interfaceCurrentUserContextType{
username:string;
}

constCurrentUserContext=createContext<CurrentUserContextType|null>(null);
constApp=()=>{
const[currentUser,setCurrentUser]=useState<CurrentUserContextType>({
username:"filiptammergard",
});

return(
<CurrentUserContext.Providervalue={currentUser}>
<MyComponent/>
</CurrentUserContext.Provider>
);
};

Now that the type of the context can benull,you'll notice that you'll get a'currentUser' is possibly 'null'TypeScript error if you try to access theusernameproperty. You can use optional chaining to accessusername:

import{useContext}from"react";

constMyComponent=()=>{
constcurrentUser=useContext(CurrentUserContext);

return<p>Name:{currentUser?.username}.</p>;
};

However, it would be preferable to not have to check fornull,since we know that the context won't benull.One way to do that is to provide a custom hook to use the context, where an error is thrown if the context is not provided:

import{createContext}from"react";

interfaceCurrentUserContextType{
username:string;
}

constCurrentUserContext=createContext<CurrentUserContextType|null>(null);

constuseCurrentUser=()=>{
constcurrentUserContext=useContext(CurrentUserContext);

if(!currentUserContext){
thrownewError(
"useCurrentUser has to be used within <CurrentUserContext.Provider>"
);
}

returncurrentUserContext;
};

Using a runtime type check in this will has the benefit of printing a clear error message in the console when a provider is not wrapping the components properly. Now it's possible to accesscurrentUser.usernamewithout checking fornull:

import{useContext}from"react";

constMyComponent=()=>{
constcurrentUser=useCurrentUser();

return<p>Username:{currentUser.username}.</p>;
};
Type assertion as an alternative

Another way to avoid having to check fornullis to use type assertion to tell TypeScript you know the context is notnull:

import{useContext}from"react";

constMyComponent=()=>{
constcurrentUser=useContext(CurrentUserContext);

return<p>Name:{currentUser!.username}.</p>;
};

Another option is to use an empty object as default value and cast it to the expected context type:

constCurrentUserContext=createContext<CurrentUserContextType>(
{}asCurrentUserContextType
);

You can also use non-null assertion to get the same result:

constCurrentUserContext=createContext<CurrentUserContextType>(null!);

When you don't know what to choose, prefer runtime checking and throwing over type asserting.

forwardRef/createRef

Check theHooks sectionforuseRef.

createRef:

import{createRef,PureComponent}from"react";

classCssThemeProviderextendsPureComponent<Props>{
privaterootRef=createRef<HTMLDivElement>();// like this
render(){
return<divref={this.rootRef}>{this.props.children}</div>;
}
}

forwardRef:

import{forwardRef,ReactNode}from"react";

interfaceProps{
children?:ReactNode;
type:"submit"|"button";
}
exporttypeRef=HTMLButtonElement;

exportconstFancyButton=forwardRef<Ref,Props>((props,ref)=>(
<buttonref={ref}className="MyClassName"type={props.type}>
{props.children}
</button>
));
Side note: therefyou get fromforwardRefis mutable so you can assign to it if needed.

This was doneon purpose.You can make it immutable if you have to - assignReact.Refif you want to ensure nobody reassigns it:

import{forwardRef,ReactNode,Ref}from"react";

interfaceProps{
children?:ReactNode;
type:"submit"|"button";
}

exportconstFancyButton=forwardRef(
(
props:Props,
ref:Ref<HTMLButtonElement>// <-- here!
)=>(
<buttonref={ref}className="MyClassName"type={props.type}>
{props.children}
</button>
)
);

If you are grabbing the props of a component that forwards refs, useComponentPropsWithRef.

Generic forwardRefs

Read more context inhttps://fettblog.eu/typescript-react-generic-forward-refs/:

Option 1 - Wrapper component
typeClickableListProps<T>={
items:T[];
onSelect:(item:T)=>void;
mRef?:React.Ref<HTMLUListElement>|null;
};

exportfunctionClickableList<T>(props:ClickableListProps<T>){
return(
<ulref={props.mRef}>
{props.items.map((item,i)=>(
<likey={i}>
<buttononClick={(el)=>props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}
Option 2 - Redeclare forwardRef
// Redeclare forwardRef
declaremodule"react"{
functionforwardRef<T,P={}>(
render:(props:P,ref:React.Ref<T>)=>React.ReactElement|null
):(props:P&React.RefAttributes<T>)=>React.ReactElement|null;
}

// Just write your components like you're used to!
import{forwardRef,ForwardedRef}from"react";

interfaceClickableListProps<T>{
items:T[];
onSelect:(item:T)=>void;
}

functionClickableListInner<T>(
props:ClickableListProps<T>,
ref:ForwardedRef<HTMLUListElement>
){
return(
<ulref={ref}>
{props.items.map((item,i)=>(
<likey={i}>
<buttononClick={(el)=>props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}

exportconstClickableList=forwardRef(ClickableListInner);
Option 3 - Call signature
// Add to `index.d.ts`
interfaceForwardRefWithGenericsextendsReact.FC<WithForwardRefProps<Option>>{
<TextendsOption>(props:WithForwardRefProps<T>):ReturnType<
React.FC<WithForwardRefProps<T>>
>;
}

exportconstClickableListWithForwardRef:ForwardRefWithGenerics=
forwardRef(ClickableList);

Credits:https://stackoverflow /a/73795494

More Info

You may also wish to doConditional Rendering withforwardRef.

Something to add? File an issue.

Portals

UsingReactDOM.createPortal:

constmodalRoot=document.getElementById("modal-root")asHTMLElement;
// assuming in your html file has a div with id 'modal-root';

exportclassModalextendsReact.Component<{children?:React.ReactNode}>{
el:HTMLElement=document.createElement("div");

componentDidMount(){
modalRoot.appendChild(this.el);
}

componentWillUnmount(){
modalRoot.removeChild(this.el);
}

render(){
returnReactDOM.createPortal(this.props.children,this.el);
}
}

View in the TypeScript Playground

Using hooks

Same as above but using hooks

import{useEffect,useRef,ReactNode}from"react";
import{createPortal}from"react-dom";

constmodalRoot=document.querySelector("#modal-root")asHTMLElement;

typeModalProps={
children:ReactNode;
};

functionModal({children}:ModalProps){
// create div element only once using ref
constelRef=useRef<HTMLDivElement|null>(null);
if(!elRef.current)elRef.current=document.createElement("div");

useEffect(()=>{
constel=elRef.current!;// non-null assertion because it will never be null
modalRoot.appendChild(el);
return()=>{
modalRoot.removeChild(el);
};
},[]);

returncreatePortal(children,elRef.current);
}

View in the TypeScript Playground

Modal Component Usage Example:

import{useState}from"react";

functionApp(){
const[showModal,setShowModal]=useState(false);

return(
<div>
// you can also put this in your static html file
<divid="modal-root"></div>
{showModal&&(
<Modal>
<div
style={{
display:"grid",
placeItems:"center",
height:"100vh",
width:"100vh",
background:"rgba(0,0,0,0.1)",
zIndex:99,
}}
>
I'm a modal!{""}
<button
style={{background:"papyawhip"}}
onClick={()=>setShowModal(false)}
>
close
</button>
</div>
</Modal>
)}
<buttononClick={()=>setShowModal(true)}>show Modal</button>
// rest of your app
</div>
);
}
Context of Example

This example is based on theEvent Bubbling Through Portalexample of React docs.

Error Boundaries

Option 1: Using react-error-boundary

React-error-boundary- is a lightweight package ready to use for this scenario with TS support built-in. This approach also lets you avoid class components that are not that popular anymore.

Option 2: Writing your custom error boundary component

If you don't want to add a new npm package for this, you can also write your ownErrorBoundarycomponent.

importReact,{Component,ErrorInfo,ReactNode}from"react";

interfaceProps{
children?:ReactNode;
}

interfaceState{
hasError:boolean;
}

classErrorBoundaryextendsComponent<Props,State>{
publicstate:State={
hasError:false
};

publicstaticgetDerivedStateFromError(_:Error):State{
// Update state so the next render will show the fallback UI.
return{hasError:true};
}

publiccomponentDidCatch(error:Error,errorInfo:ErrorInfo){
console.error("Uncaught error:",error,errorInfo);
}

publicrender(){
if(this.state.hasError){
return<h1>Sorry.. there was an error</h1>;
}

returnthis.props.children;
}
}

exportdefaultErrorBoundary;

Something to add? File an issue.

Concurrent React/React Suspense

Not written yet.watchhttps://github /sw-yx/fresh-async-reactfor more on React Suspense and Time Slicing.

Something to add? File an issue.

Troubleshooting Handbook: Types

⚠️Have you readthe TypeScript FAQYour answer might be there!

Facing weird type errors? You aren't alone. This is the hardest part of using TypeScript with React. Be patient - you are learning a new language after all. However, the more you get good at this, the less time you'll be workingagainstthe compiler and the more the compiler will be workingforyou!

Try to avoid typing withanyas much as possible to experience the full benefits of TypeScript. Instead, let's try to be familiar with some of the common strategies to solve these issues.

Union Types and Type Guarding

Union types are handy for solving some of these typing problems:

classAppextendsReact.Component<
{},
{
count:number|null;// like this
}
>{
state={
count:null,
};
render(){
return<divonClick={()=>this.increment(1)}>{this.state.count}</div>;
}
increment=(amt:number)=>{
this.setState((state)=>({
count:(state.count||0)+amt,
}));
};
}

View in the TypeScript Playground

Type Guarding:Sometimes Union Types solve a problem in one area but create another downstream. IfAandBare both object types,A | Bisn't "either A or B", it is "A or B or both at once", which causes some confusion if you expected it to be the former. Learn how to write checks, guards, and assertions (also see the Conditional Rendering section below). For example:

interfaceAdmin{
role:string;
}
interfaceUser{
email:string;
}

// Method 1: use `in` keyword
functionredirect(user:Admin|User){
if("role"inuser){
// use the `in` operator for typeguards since TS 2.7+
routeToAdminPage(user.role);
}else{
routeToHomePage(user.email);
}
}

// Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enough
functionisAdmin(user:Admin|User):userisAdmin{
return(userasany).role!==undefined;
}

View in the TypeScript Playground

Method 2 is also known asUser-Defined Type Guardsand can be really handy for readable code. This is how TS itself refines types withtypeofandinstanceof.

If you needif...elsechains or theswitchstatement instead, it should "just work", but look upDiscriminated Unionsif you need help. (See also:Basarat's writeup). This is handy in typing reducers foruseReduceror Redux.

Optional Types

If a component has an optional prop, add a question mark and assign during destructure (or use defaultProps).

classMyComponentextendsReact.Component<{
message?:string;// like this
}>{
render(){
const{message="default"}=this.props;
return<div>{message}</div>;
}
}

You can also use a!character to assert that something is not undefined, but this is not encouraged.

Something to add?File an issuewith your suggestions!

Enum Types

We recommend avoiding using enums as far as possible.

Enums have a fewdocumented issues(the TS teamagrees). A simpler alternative to enums is just declaring a union type of string literals:

exportdeclaretypePosition="left"|"right"|"top"|"bottom";

If you must use enums, remember that enums in TypeScript default to numbers. You will usually want to use them as strings instead:

exportenumButtonSizes{
default="default",
small="small",
large="large",
}

// usage
exportconstPrimaryButton=(
props:Props&React.HTMLProps<HTMLButtonElement>
)=><Buttonsize={ButtonSizes.default}{...props}/>;

Type Assertion

Sometimes you know better than TypeScript that the type you're using is narrower than it thinks, or union types need to be asserted to a more specific type to work with other APIs, so assert with theaskeyword. This tells the compiler you know better than it does.

classMyComponentextendsReact.Component<{
message:string;
}>{
render(){
const{message}=this.props;
return(
<Component2message={messageasSpecialMessageType}>{message}</Component2>
);
}
}

View in the TypeScript Playground

Note that you cannot assert your way to anything - basically it is only for refining types. Therefore it is not the same as "casting" a type.

You can also assert a property is non-null, when accessing it:

element.parentNode!.removeChild(element);//! before the period
myFunction(document.getElementById(dialog.id!)!);//! after the property accessing
letuserID!:string;// definite assignment assertion... be careful!

Of course, try to actually handle the null case instead of asserting:)

Simulating Nominal Types

TS' structural typing is handy, until it is inconvenient. However you can simulate nominal typing withtype branding:

typeOrderID=string&{readonlybrand:uniquesymbol};
typeUserID=string&{readonlybrand:uniquesymbol};
typeID=OrderID|UserID;

We can create these values with the Companion Object Pattern:

functionOrderID(id:string){
returnidasOrderID;
}
functionUserID(id:string){
returnidasUserID;
}

Now TypeScript will disallow you from using the wrong ID in the wrong place:

functionqueryForUser(id:UserID){
//...
}
queryForUser(OrderID("foobar"));// Error, Argument of type 'OrderID' is not assignable to parameter of type 'UserID'

In future you can use theuniquekeyword to brand.See this PR.

Intersection Types

Adding two types together can be handy, for example when your component is supposed to mirror the props of a native component like abutton:

exportinterfacePrimaryButtonProps{
label:string;
}
exportconstPrimaryButton=(
props:PrimaryButtonProps&React.ButtonHTMLAttributes<HTMLButtonElement>
)=>{
// do custom buttony stuff
return<button{...props}>{props.label}</button>;
};

Playgroundhere

You can also use Intersection Types to make reusable subsets of props for similar components:

typeBaseProps={
className?:string,
style?:React.CSSProperties
name:string// used in both
}
typeDogProps={
tailsCount:number
}
typeHumanProps={
handsCount:number
}
exportconstHuman=(props:BaseProps&HumanProps)=>//...
exportconstDog=(props:BaseProps&DogProps)=>//...

View in the TypeScript Playground

Make sure not to confuse Intersection Types (which areandoperations) with Union Types (which areoroperations).

Union Types

This section is yet to be written (please contribute!). Meanwhile, see ourcommentary on Union Types usecases.

The ADVANCED cheatsheet also has information on Discriminated Union Types, which are helpful when TypeScript doesn't seem to be narrowing your union type as you expect.

Overloading Function Types

Specifically when it comes to functions, you may need to overload instead of union type. The most common way function types are written uses the shorthand:

typeFunctionType1=(x:string,y:number)=>number;

But this doesn't let you do any overloading. If you have the implementation, you can put them after each other with the function keyword:

functionpickCard(x:{suit:string;card:number}[]):number;
functionpickCard(x:number):{suit:string;card:number};
functionpickCard(x):any{
// implementation with combined signature
//...
}

However, if you don't have an implementation and are just writing a.d.tsdefinition file, this won't help you either. In this case you can forego any shorthand and write them the old-school way. The key thing to remember here is as far as TypeScript is concerned,functions are just callable objects with no key:

typepickCard={
(x:{suit:string;card:number}[]):number;
(x:number):{suit:string;card:number};
// no need for combined signature in this form
// you can also type static properties of functions here eg `pickCard.wasCalled`
};

Note that when you implement the actual overloaded function, the implementation will need to declare the combined call signature that you'll be handling, it won't be inferred for you. You can readily see examples of overloads in DOM APIs, e.g.createElement.

Read more about Overloading in the Handbook.

Using Inferred Types

Leaning on TypeScript's Type Inference is great... until you realize you need a type that was inferred, and have to go back and explicitly declare types/interfaces so you can export them for reuse.

Fortunately, withtypeof,you won't have to do that. Just use it on any value:

const[state,setState]=useState({
foo:1,
bar:2,
});// state's type inferred to be {foo: number, bar: number}

constsomeMethod=(obj:typeofstate)=>{
// grabbing the type of state even though it was inferred
// some code using obj
setState(obj);// this works
};

Using Partial Types

Working with slicing state and props is common in React. Again, you don't really have to go and explicitly redefine your types if you use thePartialgeneric type:

const[state,setState]=useState({
foo:1,
bar:2,
});// state's type inferred to be {foo: number, bar: number}

// NOTE: stale state merging is not actually encouraged in useState
// we are just demonstrating how to use Partial here
constpartialStateUpdate=(obj:Partial<typeofstate>)=>
setState({...state,...obj});

// later on...
partialStateUpdate({foo:2});// this works
Minor caveats on usingPartial

Note that there are some TS users who don't agree with usingPartialas it behaves today. Seesubtle pitfalls of the above example here,and check out this long discussion onwhy @types/react uses Pick instead of Partial.

The Types I need weren't exported!

This can be annoying but here are ways to grab the types!

  • Grabbing the Prop types of a component: UseReact.ComponentPropsandtypeof,and optionallyOmitany overlapping types
import{Button}from"library";// but doesn't export ButtonProps! oh no!
typeButtonProps=React.ComponentProps<typeofButton>;// no problem! grab your own!
typeAlertButtonProps=Omit<ButtonProps,"onClick">;// modify
constAlertButton=(props:AlertButtonProps)=>(
<ButtononClick={()=>alert("hello")}{...props}/>
);

You may also useComponentPropsWithoutRef(instead of ComponentProps) andComponentPropsWithRef(if your component specifically forwards refs)

  • Grabbing the return type of a function: useReturnType:
// inside some library - return type { baz: number } is inferred but not exported
functionfoo(bar:string){
return{baz:1};
}

// inside your app, if you need { baz: number }
typeFooReturn=ReturnType<typeoffoo>;// { baz: number }

In fact you can grab virtually anything public:see this blogpost from Ivan Koshelev

functionfoo(){
return{
a:1,
b:2,
subInstArr:[
{
c:3,
d:4,
},
],
};
}

typeInstType=ReturnType<typeoffoo>;
typeSubInstArr=InstType["subInstArr"];
typeSubInstType=SubInstArr[0];

letbaz:SubInstType={
c:5,
d:6,// type checks ok!
};

//You could just write a one-liner,
//But please make sure it is forward-readable
//(you can understand it from reading once left-to-right with no jumps)
typeSubInstType2=ReturnType<typeoffoo>["subInstArr"][0];
letbaz2:SubInstType2={
c:5,
d:6,// type checks ok!
};
  • TS also ships with aParametersutility type for extracting the parameters of a function
  • for anything more "custom", theinferkeyword is the basic building block for this, but takes a bit of getting used to. Look at the source code for the above utility types, andthis exampleto get the idea. Basaratalso has a good video oninfer.

The Types I need don't exist!

What's more annoying than modules with unexported types? Modules that areuntyped!

Before you proceed - make sure you have checked that types don't exist inDefinitelyTypedorTypeSearch

Fret not! There are more than a couple of ways in which you can solve this problem.

Slappinganyon everything

Alazierway would be to create a new type declaration file, saytypedec.d.ts– if you don't already have one. Ensure that the path to file is resolvable by TypeScript by checking theincludearray in thetsconfig.jsonfile at the root of your directory.

// inside tsconfig.json
{
//...
"include":[
"src"// automatically resolves if the path to declaration is src/typedec.d.ts
]
//...
}

Within this file, add thedeclaresyntax for your desired module, saymy-untyped-module– to the declaration file:

// inside typedec.d.ts
declaremodule"my-untyped-module";

This one-liner alone is enough if you just need it to work without errors. A even hackier, write-once-and-forget way would be to use"*"instead which would then apply theAnytype for all existing and future untyped modules.

This solution works well as a workaround if you have less than a couple untyped modules. Anything more, you now have a ticking type-bomb in your hands. The only way of circumventing this problem would be to define the missing types for those untyped modules as explained in the following sections.

Autogenerate types

You can use TypeScript with--allowJsand--declarationto see TypeScript's "best guess" at the types of the library.

If this doesn't work well enough, usedts-gento use the runtime shape of the object to accurately enumerate all available properties. This tends to be very accurate, BUT the tool does not yet support scraping JSDoc comments to populate additional types.

npm install -g dts-gen
dts-gen -m<your-module>

There are other automated JS to TS conversion tools and migration strategies - seeour MIGRATION cheatsheet.

Typing Exported Hooks

Typing Hooks is just like typing pure functions.

The following steps work under two assumptions:

  • You have already created a type declaration file as stated earlier in the section.
  • You have access to the source code - specifically the code that directly exports the functions you will be using. In most cases, it would be housed in anindex.jsfile. Typically you need a minimum oftwotype declarations (one forInput Propand the other forReturn Prop) to define a hook completely. Suppose the hook you wish to type follows the following structure,
//...
constuseUntypedHook=(prop)=>{
// some processing happens here
return{
/* ReturnProps */
};
};
exportdefaultuseUntypedHook;

then, your type declaration should most likely follow the following syntax.

declaremodule'use-untyped-hook'{
exportinterfaceInputProps{...}// type declaration for prop
exportinterfaceReturnProps{...}// type declaration for return props
exportdefaultfunctionuseUntypedHook(
prop:InputProps
//...
):ReturnProps;
}
For instance, theuseDarkMode hookexports the functions that follows a similar structure.
// inside src/index.js
constuseDarkMode=(
initialValue=false,// -> input props / config props to be exported
{
// -> input props / config props to be exported
element,
classNameDark,
classNameLight,
onChange,
storageKey="darkMode",
storageProvider,
global,
}={}
)=>{
//...
return{
// -> return props to be exported
value:state,
enable:useCallback(()=>setState(true),[setState]),
disable:useCallback(()=>setState(false),[setState]),
toggle:useCallback(()=>setState((current)=>!current),[setState]),
};
};
exportdefaultuseDarkMode;

As the comments suggest, exporting these config props and return props following the aforementioned structure will result in the following type export.

declaremodule"use-dark-mode"{
/**
* A config object allowing you to specify certain aspects of `useDarkMode`
*/
exportinterfaceDarkModeConfig{
classNameDark?:string;// A className to set "dark mode". Default = "dark-mode".
classNameLight?:string;// A className to set "light mode". Default = "light-mode".
element?:HTMLElement;// The element to apply the className. Default = `document.body`
onChange?:(val?:boolean)=>void;// Override the default className handler with a custom callback.
storageKey?:string;// Specify the `localStorage` key. Default = "darkMode". Set to `null` to disable persistent storage.
storageProvider?:WindowLocalStorage;// A storage provider. Default = `localStorage`.
global?:Window;// The global object. Default = `window`.
}
/**
* An object returned from a call to `useDarkMode`.
*/
exportinterfaceDarkMode{
readonlyvalue:boolean;
enable:()=>void;
disable:()=>void;
toggle:()=>void;
}
/**
* A custom React Hook to help you implement a "dark mode" component for your application.
*/
exportdefaultfunctionuseDarkMode(
initialState?:boolean,
config?:DarkModeConfig
):DarkMode;
}
Typing Exported Components

In case of typing untyped class components, there's almost no difference in approach except for the fact that after declaring the types, you export the extend the type usingclass UntypedClassComponent extends React.Component<UntypedClassComponentProps, any> {}whereUntypedClassComponentPropsholds the type declaration.

For instance,sw-yx's Gist on React Router 6 typesimplemented a similar method for typing the then untyped RR6.

declaremodule"react-router-dom"{
import*asReactfrom'react';
//...
typeNavigateProps<T>={
to:string|number,
replace?:boolean,
state?:T
}
//...
exportclassNavigate<T=any>extendsReact.Component<NavigateProps<T>>{}
//...

For more information on creating type definitions for class components, you can refer to thispostfor reference.

Frequent Known Problems with TypeScript

Just a list of stuff that React developers frequently run into, that TS has no solution for. Not necessarily TSX only.

TypeScript doesn't narrow after an object element null check

https://pbs.twimg.com/media/E0u6b9uUUAAgwAk?format=jpg&name=medium

Ref:https://mobile.twitter /tannerlinsley/status/1390409931627499523.see alsomicrosoft/TypeScript#9998

TypeScript doesn't let you restrict the type of children

Guaranteeing typesafety for this kind of API isn't possible:

<Menu>
<MenuItem/>{/* ok */}
<MenuLink/>{/* ok */}
<div>{/* error */}
</Menu>

Source:https://twitter /ryanflorence/status/1085745787982700544?s=20

Troubleshooting Handbook: Operators

  • typeofandinstanceof:type query used for refinement
  • keyof:get keys of an object.keyof Tis an operator to tell you what values ofkcan be used forobj[k].
  • O[K]:property lookup
  • [K in O]:mapped types
  • +or-orreadonlyor?:addition and subtraction and readonly and optional modifiers
  • x? Y: Z:Conditional types for generic types, type aliases, function parameter types
  • !:Nonnull assertion for nullable types
  • =:Generic type parameter default for generic types
  • as:type assertion
  • is:type guard for function return types

Conditional Types are a difficult topic to get around so here are some extra resources:

Troubleshooting Handbook: Utilities

These are all built in,see source in es5.d.ts:

  • Awaited:emulate the behavior ofawait
  • Capitalize:convert first character of string literal type to uppercase
  • ConstructorParameters:a tuple of class constructor's parameter types
  • Exclude:exclude a type from another type
  • Extract:select a subtype that is assignable to another type
  • InstanceType:the instance type you get from anewing a class constructor
  • Lowercase:convert string literal type to lowercase
  • NonNullable:excludenullandundefinedfrom a type
  • Omit:construct a type with the properties of another type.
  • OmitThisParameter:remove the 'this' parameter from a function type.
  • Parameters:a tuple of a function's parameter types
  • Partial:Make all properties in an object optional
  • Readonly:Make all properties in an object readonly
  • ReadonlyArray:Make an immutable array of the given type
  • Pick:A subtype of an object type with a subset of its keys
  • Record:A map from a key type to a value type
  • Required:Make all properties in an object required
  • ReturnType:A function's return type
  • ThisParameterType:extract the type of the 'this' parameter of a function type
  • ThisType:marker for contextual 'this' type
  • Uncapitalize:convert first character of string literal type to lowercase
  • Uppercase:convert string literal type to uppercase

Troubleshooting Handbook: tsconfig.json

You can findall the Compiler options in the TypeScript docs.The new TS docs also has per-flag annotations of what each does.This is the setup I roll with for APPS (not libraries - for libraries you may wish to see the settings we use intsdx):

{
"compilerOptions":{
"incremental":true,
"outDir":"build/lib",
"target":"es5",
"module":"esnext",
"lib":["DOM","ESNext"],
"sourceMap":true,
"importHelpers":true,
"declaration":true,
"rootDir":"src",
"strict":true,
"noUnusedLocals":true,
"noUnusedParameters":true,
"noImplicitReturns":true,
"noFallthroughCasesInSwitch":true,
"allowJs":false,
"jsx":"react",
"moduleResolution":"node",
"baseUrl":"src",
"forceConsistentCasingInFileNames":true,
"esModuleInterop":true,
"suppressImplicitAnyIndexErrors":true,
"allowSyntheticDefaultImports":true,
"experimentalDecorators":true
},
"include":["src/**/*"],
"exclude":["node_modules","build","scripts"]
}

You can find morerecommended TS config here.

Please open an issue and discuss if there are better recommended choices for React.

Selected flags and why we like them:

  • esModuleInterop:disables namespace imports (import * as foo from "foo") and enables CJS/AMD/UMD style imports (import fs from "fs")
  • strict:strictPropertyInitializationforces you to initialize class properties or explicitly declare that they can be undefined. You can opt out of this with a definite assignment assertion.
  • "typeRoots": [ "./typings", "./node_modules/@types" ]:By default, TypeScript looks innode_modules/@typesand parent folders for third party type declarations. You may wish to override this default resolution so you can put all your global type declarations in a specialtypingsfolder.

Compilation time grows linearly with size of codebase. For large projects, you will want to useProject References.See ourADVANCEDcheatsheet for commentary.

Troubleshooting Handbook: Fi xing bugs in official typings

If you run into bugs with your library's official typings, you can copy them locally and tell TypeScript to use your local version using the "paths" field. In yourtsconfig.json:

{
"compilerOptions":{
"paths":{
"mobx-react":["../typings/modules/mobx-react"]
}
}
}

Thanks to @adamrackis for the tip.

If you just need to add an interface, or add missing members to an existing interface, you don't need to copy the whole typing package. Instead, you can usedeclaration merging:

// my-typings.ts
declaremodule"plotly.js"{
interfacePlotlyHTMLElement{
removeAllListeners():void;
}
}

// MyComponent.tsx
import{PlotlyHTMLElement}from"plotly.js";

constf=(e:PlotlyHTMLElement)=>{
e.removeAllListeners();
};

You dont always have to implement the module, you can simply import the module asanyfor a quick start:

// my-typings.ts
declaremodule"plotly.js";// each of its imports are `any`

Because you don't have to explicitly import this, this is known as anambient module declaration.You can do AMD's in a script-mode.tsfile (no imports or exports), or a.d.tsfile anywhere in your project.

You can also do ambient variable and ambient type declarations:

// ambient utility type
typeToArray<T>=Textendsunknown[]?T:T[];
// ambient variable
declareletprocess:{
env:{
NODE_ENV:"development"|"production";
};
};
process={
env:{
NODE_ENV:"production",
},
};

You can see examples of these included in the built in type declarations in thelibfield oftsconfig.json

Troubleshooting Handbook: Globals, Images and other non-TS files

Usedeclaration merging.

If, say, you are using a third party JS script that attaches on to thewindowglobal, you can extendWindow:

declareglobal{
interfaceWindow{
MyVendorThing:MyVendorType;
}
}

Likewise if you wish to "import" an image or other non TS/TSX file:

// declaration.d.ts
// anywhere in your project, NOT the same name as any of your.ts/tsx files
declaremodule"*.png";

// importing in a tsx file
import*aslogofrom"./logo.png";

Note thattsccannot bundle these files for you, you will have to use Webpack or Parcel.

Related issue:microsoft/TypeScript-React-Starter#12andStackOverflow

Editor Tooling and Integration

You are free to use this repo's TSX logo if you wish:

https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png

You may also wish to use alternative logos -jsx-tsx-logos

https://github.com/Protectator/jsx-tsx-logos/raw/master/example.png

Linting

⚠️Note thatTSLint is now in maintenance and you should try to use ESLint instead.If you are interested in TSLint tips, please check this PR from@azdanov.The rest of this section just focuses on ESLint.You can convert TSlint to ESlint with this tool.

⚠️This is an evolving topic.typescript-eslint-parseris no longer maintained andwork has recently begun ontypescript-eslintin the ESLint communityto bring ESLint up to full parity and interop with TSLint.

Follow the TypeScript + ESLint docs athttps://github /typescript-eslint/typescript-eslint:

yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint

add alintscript to yourpackage.json:

"scripts":{
"lint":"eslint 'src/**/*.ts'"
},

and a suitable.eslintrc.js(using.jsover.jsonhere so we can add comments):

module.exports={
env:{
es6:true,
node:true,
jest:true,
},
extends:"eslint:recommended",
parser:"@typescript-eslint/parser",
plugins:["@typescript-eslint"],
parserOptions:{
ecmaVersion:2017,
sourceType:"module",
},
rules:{
indent:["error",2],
"linebreak-style":["error","unix"],
quotes:["error","single"],
"no-console":"warn",
"no-unused-vars":"off",
"@typescript-eslint/no-unused-vars":[
"error",
{vars:"all",args:"after-used",ignoreRestSiblings:false},
],
"@typescript-eslint/explicit-function-return-type":"warn",// Consider using explicit annotations for object literals and function return types even when they can be inferred.
"no-empty":"warn",
},
};

Most of this is taken fromthetsdxPRwhich is forlibraries.

More.eslintrc.jsonoptions to consider with more options you may want forapps:

{
"extends":[
"airbnb",
"prettier",
"prettier/react",
"plugin:prettier/recommended",
"plugin:jest/recommended",
"plugin:unicorn/recommended"
],
"plugins":["prettier","jest","unicorn"],
"parserOptions":{
"sourceType":"module",
"ecmaFeatures":{
"jsx":true
}
},
"env":{
"es6":true,
"browser":true,
"jest":true
},
"settings":{
"import/resolver":{
"node":{
"extensions":[".js",".jsx",".ts",".tsx"]
}
}
},
"overrides":[
{
"files":["**/*.ts","**/*.tsx"],
"parser":"typescript-eslint-parser",
"rules":{
"no-undef":"off"
}
}
]
}

Another great resource is"Using ESLint and Prettier in a TypeScript Project"by @robertcoopercode.

Wes Bos is also working onTypeScript support for his eslint+prettier config.

If you're looking for information on Prettier, check out thePrettierguide.

Other React + TypeScript resources

Recommended React + TypeScript talks

Time to Really Learn TypeScript

Believe it or not, we have only barely introduced TypeScript here in this cheatsheet. If you are still facing TypeScript troubleshooting issues, it is likely that your understanding of TS is still too superficial.

There is a whole world of generic type logic that you will eventually get into, however it becomes far less dealing with React than just getting good at TypeScript so it is out of scope here. But at least you can get productive in React now:)

It is worth mentioning some resources to help you get started:

Example App

My question isn't answered here!

Contributors

This project follows theall-contributorsspecification. SeeCONTRIBUTORS.mdfor the full list. Contributions of any kind welcome!