Skip to content

jlismore/react-typescript-cheatsheet

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 

Repository files navigation

đź‘‹ This repo is maintained by @swyx, @IslamAttrash and @ferdaber, we're so happy you want to try out TypeScript with React! This is meant to be a guide for React developers familiar with the concepts of TypeScript but who are just getting started writing their first React + TypeScript apps. If you see anything wrong or missing, please file an issue! đź‘Ť

Translations:


Two Levels of React + TypeScript Cheatsheets

  • The Basic Cheatsheet (/README.md) is focused on helping React devs just start using TS in React apps
    • 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 learning too much TS.
  • The Advanced Cheatsheet (/ADVANCED.md) helps show and explain advanced usage of generic types for people writing reusable type utilities/functions/render prop/higher order components and TS+React libraries.
    • It also has miscellaneous tips and tricks for pro users.
    • Advice for contributing to DefinitelyTyped
    • The goal is to take full advantage of TypeScript.

Basic Cheatsheet Table of Contents

Expand Table of Contents

Section 1: Setup

Prerequisites

  1. good understanding of React
  2. familiarity with TypeScript Types (2ality's guide is helpful)
  3. having read the TypeScript section in the official React docs.

This guide will always assume you are starting with the latest TypeScript version. Notes for older versions will be in expandable <details> tags.

React + TypeScript Starter Kits

  1. Create React App v2.1+ with Typescript: npm create react-app my-new-react-typescript-app --typescript
  1. Basarat's guide for manual setup of React + TypeScript + Webpack + Babel

Import React

import * as React from 'react';
import * as ReactDOM from 'react-dom';

In TypeScript 2.7+, you can run TypeScript with --allowSyntheticDefaultImports (or add "allowSyntheticDefaultImports": true to tsconfig) to import like in regular jsx:

import React from 'react';
import ReactDOM from 'react-dom';
Explanation

Why allowSyntheticDefaultImports over esModuleInterop? Daniel Rosenwasser has said that it's better for webpack/parcel. For more discussion check out wmonk/create-react-app-typescript#214

Please PR or File an issue with your suggestions!

Section 2: Getting Started

Function Components

You can specify the type of props as you use them and rely on type inference:

const App = ({ message }: { message: string }) => <div>{message}</div>;

Or you can use the provided generic type for function components:

const App: React.FC<{ message: string }> = ({ message }) => <div>{message}</div>; // React.FunctionComponent also works
What's the difference?

The former pattern is shorter, so why would people use React.FunctionComponent at all?

  • If you need to use children property inside the function body, in the former case it has to be added explicitly. FunctionComponent<T> already includes the correctly typed children property which then doesn't have to become part of your type.
  • Typing your function explicitly will also give you typechecking and autocomplete on its static properties, like displayName, propTypes, and defaultProps.
  • In future, it will also set readonly on your props just like React.Component<T> does.
const Title: React.FunctionComponent<{ title: string }> = ({ children, title }) => ( 
    <div title={title}>{children}</div>
);

If you want to use the function keyword instead of an arrow function, you can use this syntax (using a function expression, instead of declaration):

const App: React.FunctionComponent<{ message: string }> = function App({ message }) {
  return <div{message}</div>;
}
Minor Pitfalls

These patterns are not supported:

Conditional rendering

const MyConditionalComponent = ({ shouldRender = false }) => shouldRender ? <div /> : false // don't do this in JS either
const el = <MyConditionalComponent /> // throws an error

This is because due to limitations in the compiler, function components cannot return anything other than a JSX expression or null, otherwise it complains with a cryptic error message saying that the other type is not assignable to Element.

const MyArrayComponent = () => Array(5).fill(<div />)
const el2 = <MyArrayComponent /> // throws an error

Array.fill

Unfortunately just annotating the function type will not help so if you really need to return other exotic types that React supports, you'd need to perform a type assertion:

const MyArrayComponent = () => Array(5).fill(<div />) as any as JSX.Element

See commentary by @ferdaber here.

Hooks

Hooks are supported in @types/react from v16.7 up.

useState

Type inference works very well most of the time:

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

See also the Using Inferred Types section 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<IUser | null>(null);

// later...
setUser(newUser)

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, assert or define the function return types:

export function useLoading() {
  const [isLoading, setState] = React.useState(false);
  const load = (aPromise: Promise<any>) => {
    setState(true);
    return aPromise.finally(() => setState(false));
  };
  return [isLoading, load] as [
    boolean,
    (aPromise: Promise<any>) => Promise<any>
  ];
}

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.Component is a generic type (aka React.Component<PropType, StateType>), so you want to provide it with (optional) prop and state type parameters:

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

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

Why annotate `state` twice?

It isn't strictly necessary to annotate the state class property, but it allows better type inference when accessing this.state and also initializing the state.

This is because they work in two different ways, the 2nd generic type parameter will allow this.setState() to work correctly, because that method comes from the base class, but initializing state inside 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 for readonly

You often see sample code include readonly to mark props and state immutable:

type MyProps = {
  readonly message: string
}
type MyState = {
  readonly count: number
}

This is not necessary as React.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:

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

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

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

Something to add? File an issue.

Typing defaultProps

For Typescript 3.0+, type inference should work, although some edge cases are still problematic. Just type your props like normal.

export type Props = {
    name: string;
}

export class Greet extends React.Component<Props> {
    render() {
        const { name } = this.props;
        return <div>Hello ${name.toUpperCase()}!</div>;
    }
    static defaultProps = { name: "world"};
}

// Type-checks! No type assertions needed!
let el = <Greet />
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:

type Props = Required<typeof MyComponent.defaultProps> & { /* additional props here */ }

export class MyComponent extends React.Component<Props> {
  static defaultProps = {
    foo: 'foo'
  }
}

Our former recommendation used the Partial type feature 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!

interface IMyComponentProps {
  firstProp?: string;
  secondProp: IPerson[];
}

export class MyComponent extends React.Component<IMyComponentProps> {
  public static defaultProps: Partial<IMyComponentProps> = {
    firstProp: "default",
  };
}

The problem with this approach is it causes complex issues with the type inference working with 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 here.

Something to add? File an issue.

Types or Interfaces?

interfaces are different from types in TypeScript, but they can be used for very similar things as far as common React uses cases are concerned. Here's a helpful rule of thumb:

  • always use interface for public API's definition when authoring a library or 3rd party ambient type definitions.

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

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

Useful table for Types vs Interfaces It's a nuanced topic, don't get too hung up on it. Here's a handy graphic:

https://pbs.twimg.com/media/DwV-oOsXcAIct2q.jpg (source: Karol Majewski)

Something to add? File an issue.

Basic Prop Types Examples

type AppProps = {
  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',
  /** any object as long as you dont use its properties (not common) */
  obj: object, 
  obj2: {}, // same
  /** an object with defined properties (preferred) */
  obj3: {
   id: string,
   title: string
  },
  /** array of objects! (common) */
  objArr: {
   id: string,
   title: string
  }[],
  /** any function as long as you don't invoke it (not recommended) */
  onSomething: Function,
  /** function that doesn't take or return anything (VERY COMMON) */
  onClick: () => void,
  /** function with named prop (VERY COMMON) */
  onChange: (id: number) => void,
  /** an optional prop (VERY COMMON!) */
  optional?: OptionalType,
}

Notice we have used the TSDoc /** comment */ style here on each prop. You can and are encouraged to leave descriptive comments on reusable components. For a fuller example and discussion, see our Commenting Components section in the Advanced Cheatsheet.

Useful React Prop Type Examples

export declare interface AppProps {
  children1: JSX.Element;                            // bad, doesnt account for arrays
  children2: JSX.Element | JSX.Element[];            // meh, doesnt accept functions
  children3: React.ReactChild | React.ReactChildren; // better, but doesnt accept strings
  children: React.ReactNode;                         // best, accepts everything
  style?: React.CSSProperties;                       // to pass through style props
  onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target
  props: Props & React.PropsWithoutRef<JSX.IntrinsicElements['button']>  // to impersonate all the props of a button element without its ref
}
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 by React.createElement. Regardless of what a component ends up rendering, React.createElement always returns an object, which is the JSX.Element interface, but React.ReactNode is the set of all possible return values of a component.

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

Something to add? File an issue.

Forms and Events

If performance is not an issue, inlining handlers is easiest as you can just use type inference:

const el = <button onClick={event => {/* ... */}} />

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 an onChange for a form event:

class App extends React.Component<{}, { // no props
    text: string,
  }> {
  state = {
    text: ''
  }
  
  // typing on RIGHT hand side of =
  onChange = (e: React.FormEvent<HTMLInputElement>): void => {
    this.setState({text: e.currentTarget.value})
  }
  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.text}
          onChange={this.onChange}
        />
      </div>
    );
  }
}

Instead of typing the arguments and return values with React.FormEvent<> and void, 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>): void and the second method enforces a type of the delegate provided by @types/react. So React.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.

Context

Contributed by: @jpavon

Using the new context API React.createContext:

interface ProviderState {
  themeColor: string
}

interface UpdateStateArg {
  key: keyof ProviderState
  value: string
}

interface ProviderStore {
  state: ProviderState
  update: (arg: UpdateStateArg) => void
}

const Context = React.createContext({} as ProviderStore) // type assertion on empty object

class Provider extends React.Component<{}, ProviderState> {
  public readonly state = {
    themeColor: 'red'
  }

  private update = ({ key, value }: UpdateStateArg) => {
    this.setState({ [key]: value })
  }

  public render() {
    const store: ProviderStore = {
      state: this.state,
      update: this.update
    }

    return (
      <Context.Provider value={store}>
        {this.props.children}
      </Context.Provider>
    )
  }
}

const Consumer = Context.Consumer

Something to add? File an issue.

forwardRef/createRef

createRef:

class CssThemeProvider extends React.PureComponent<Props> {
  private rootRef = React.createRef<HTMLDivElement>(); // like this
  render() {
    return <div ref={this.rootRef}>{this.props.children}</div>;
  }
}

forwardRef:

type Props = { children: React.ReactNode; type: 'submit' | 'button' }
export type Ref = HTMLButtonElement
export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
  <button ref={ref} className="MyClassName" type={props.type}>
    {props.children}
  </button>
))

More info: https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315

Something to add? File an issue.

Portals

Using ReactDOM.createPortal:

const modalRoot = document.getElementById('modal-root') as HTMLElement;
// assuming in your html file has a div with id 'modal-root';

export class Modal extends React.Component {
    el: HTMLElement = document.createElement('div');

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

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

    render() {
        return ReactDOM.createPortal(
            this.props.children,
            this.el
        )
    }
}
Context of Example

This example is based on the Event Bubbling Through Portal example of React docs.

Error Boundaries

Not written yet.

Something to add? File an issue.

Concurrent React/React Suspense

Not written yet. watch https://github.com/sw-yx/fresh-async-react for more on React Suspense and Time Slicing.

Something to add? File an issue.

Basic Troubleshooting Handbook: Types

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

Try to avoid typing with any as 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:

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

Type Guarding: Sometimes Union Types solve a problem in one area but create another downstream. Learn how to write checks, guards, and assertions (also see the Conditional Rendering section below). For example:

interface Admin {
  role: string:
}
interface User {
  email: string;
}

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

// Method 2: custom type guard, does the same thing in older TS versions or where `in` isnt enough
function isAdmin(usr: Admin | User): usr is Admin {
  return (<Admin>usr).role !==undefined
}

If you need if/elseif chains or the switch statement instead, it should "just work", but look up Discriminated Unions if you need help. (See also: Basarat's writeup). This is handy in typing reducers for useReducer or Redux.

Optional Types

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

class MyComponent extends React.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 issue with your suggestions!

Enum Types

Enums in TypeScript default to numbers. You will usually want to use them as strings instead:

export enum ButtonSizes {
  default = 'default',
  small = 'small',
  large = 'large'
}

Usage:

export const PrimaryButton = (
  props: Props & React.HTMLProps<HTMLButtonElement>
) => (
  <Button
    size={ButtonSizes.default}
    {...props}
  />
);

A simpler alternative to enum is just declaring a bunch of strings with union:

export declare type Position = 'left' | 'right' | 'top' | 'bottom';
Brief Explanation

This is handy because TypeScript will throw errors when you mistype a string for your props.

Type Assertion

Sometimes TypeScript is just getting your type wrong, or union types need to be asserted to a more specific type to work with other APIs, so assert with the as keyword. This tells the compiler you know better than it does.

class MyComponent extends React.Component<{
  message: string,
}> {
  render() {
    const {message} = this.props;
    return (
      <Component2 message={message as SpecialMessageType}>{message}</Component2>
    );
  }
}
Explanation

Note that this is not the same as casting.

Something to add? Please PR or File an issue with your suggestions!

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 a button:

export interface Props {
  label: string;
}
export const PrimaryButton = (
  props: Props & React.HTMLProps<HTMLButtonElement> // adding my Props together with the @types/react button provided props
) => (
  <Button
    {...props}
  />
);

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, with typeof, you won't have to do that. Just use it on any value:

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

const someMethod = (obj: typeof state) => {  // 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 the Partial generic type:

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

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

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

Note that there are some TS users who don't agree with using Partial as it behaves today. See subtle pitfalls of the above example here, and check out this long discussion on why @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: Use typeof, and optionally Omit any overlapping types
import { Button } from 'library' // but doesn't export ButtonProps
type ButtonProps = React.ComponentProps<typeof Button> // grab your own
type AlertButtonProps = Omit<ButtonProps, 'onClick'> // modify
const AlertButton: React.FC<AlertButtonProps> = props => (
  <Button onClick={() => alert('hello')} {...props} />
)
  • Grabbing the return type of a function: use ReturnType:
// inside some library - return type { baz: number } is inferred but not exported
function foo(bar: string) {
  return { baz: 1 }
}

//  inside your app, if you need { baz: number }
type FooReturn = ReturnType<typeof foo> // { baz: number }

Troubleshooting Handbook: TSLint

Sometimes TSLint is just getting in the way. Judicious turning off of things can be helpful. Here are useful tslint disables you may use:

  • /* tslint:disable */ total disable
  • // tslint:disable-line just this line
  • /* tslint:disable:semicolon */ sometimes prettier adds semicolons and tslint doesn't like it.
  • /* tslint:disable:no-any */ disable tslint restriction on no-any when you WANT to use any
  • /* tslint:disable:max-line-length */ disable line wrapping linting

so on and so forth. there are any number of things you can disable, usually you can look at the error raised in VScode or whatever the tooling and the name of the error will correspond to the rule you should disable.

Explanation

This is not yet written. Please PR or File an issue with your suggestions!

Troubleshooting Handbook: tsconfig.json

You can find all the Compiler options in the Typescript docs. This is the setup I roll with for my component library:

{
  "compilerOptions": {
    "outDir": "build/lib",
    "module": "commonjs",
    "target": "es5",
    "lib": ["es5", "es6", "es7", "es2017", "dom"],
    "sourceMap": true,
    "allowJs": false,
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "baseUrl": "src",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "strict": true,
    "esModuleInterop": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "declaration": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "build", "scripts"]
}

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: strictPropertyInitialization forces you to initialize class properties or explicitly declare that they can be undefined. You can opt out of this with a definite assignment assertion.

Troubleshooting Handbook: 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 your tsconfig.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 use declaration merging:

// my-typings.ts
declare module 'plotly.js' {
  interface PlotlyHTMLElement {
    removeAllListeners(): void;
  }
}

// MyComponent.tsx
import { PlotlyHTMLElement } from 'plotly.js';
import './my-typings';
const f = (e: PlotlyHTMLElement) => { e.removeAllListeners(); }
Explanation

This is not yet written. Please PR or File an issue with your suggestions!

Recommended React + TypeScript codebases to learn from

React Boilerplates:

React Native Boilerplates: contributed by @spoeck

Other React + TypeScript resources

Recommended React + TypeScript talks

  • Please help contribute this new section!

Time to Really Learn TypeScript

Believe it or not, we have only barely introduced TypeScript here in this cheatsheet. 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:

My question isn't answered here!

About

a cheatsheet for react users using typescript with react for the first (or nth!) time

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published