# react-typescript-cheatsheet **Repository Path**: mirrors_fkhadra/react-typescript-cheatsheet ## Basic Information - **Project Name**: react-typescript-cheatsheet - **Description**: a cheatsheet for react users using typescript with react for the first (or nth!) time. - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-08-08 - **Last Updated**: 2026-02-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README
Table of Contents - [Prerequisites](#prerequisites) - [React + Typescript Starter Kits](#react---typescript-starter-kits) - [Import React](#import-react) - [Stateless Functional Components](#stateless-functional-components) - [Stateful Class-based Components](#stateful-class-based-components) - [Extracting Prop Types](#extracting-prop-types) - [Basic Prop Types Examples](#basic-prop-types-examples) - [Useful React Type Examples](#useful-react-type-examples) - [Forms and Events](#forms-and-events) - [Higher Order Components/Render Props](#higher-order-components-render-props) - [References/createRef](#references-createref) - [Component/Design System Development](#component-design-system-development) - [Building](#building) - [Prettier + TSLint](#prettier---tslint) - [Troubleshooting Handbook: Types](#troubleshooting-handbook--types) * [Union types](#union-types) * [Optional Types](#optional-types) * [Enum Types](#enum-types) * [Type Casting](#type-casting) * [Intersection Types](#intersection-types) * [Omit attribute from a type](#omit-attribute-from-a-type) - [Troubleshooting Handbook: TSLint](#troubleshooting-handbook--tslint) - [Troubleshooting Handbook: tsconfig.json](#troubleshooting-handbook--tsconfigjson) - [Recommended React + Typescript codebases to learn from](#recommended-react---typescript-codebases-to-learn-from) - [People you can ask React + Typescript questions about](#people-you-can-ask-react---typescript-questions-about) - [My question isn't answered here!](#my-question-isn-t-answered-here-)
# Prerequisites 1. good understanding of [React](https://reactjs.org) 2. familiarity with [Typescript Types](https://www.typescriptlang.org/docs/handbook/basic-types.html) 3. having read [the Typescript section in the official React docs](https://reactjs.org/docs/static-type-checking.html#typescript). 4. (optional) Read Microsoft's [TypeScript-React-Starter](https://github.com/Microsoft/TypeScript-React-Starter#typescript-react-starter) docs. # React + Typescript Starter Kits 1. is the officially recommended Typescript fork of `create-react-app`. 2. sets up a React + Typescript app with Parcel :) 3. for manual setup of React + Typescript + Webpack + Babel In particular, make sure that you have `@types/react` and `@types/react-dom` installed. [Read more about the DefinitelyTyped project if you are unfamiliar](https://definitelytyped.org/). # Import React ```tsx import * as React from 'react'; import * as ReactDOM from 'react-dom'; ``` In [TypeScript 2.7+](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html), you can run Typescript with `--allowSyntheticDefaultImports` (or add `"allowSyntheticDefaultImports": true` to tsconfig) to import like in regular jsx: ```tsx import React from 'react'; import ReactDOM from 'react-dom'; ```
Explanation Why not `esModuleInterop`? [Daniel Rosenwasser](https://twitter.com/drosenwasser/status/1003097042653073408) has said that it's better for webpack/parcel. For more discussion check out Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Stateless Functional Components You can specify the type of props as you destructure them: ```tsx const App = ({ message }: { message: string }) =>
{message}
; ``` Or you can use the provided generic type for functional components: ```tsx const App: React.SFC<{ message: string }> = ({ message }) =>
{message}
; ``` Quite frankly I prefer the former pattern as it's shorter.
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Stateful Class-based Components Within Typescript, `React.Component` is a generic type (aka `React.Component`), so you actually want to provide it with prop and (optionally) state types: ```tsx class App extends React.Component<{ message: string, // it takes one prop called 'message' which is a string type }> { render() { return (
{this.props.message}
); } } ``` If the component has state, here's how to add the types for the state: ```tsx class App extends React.Component<{ message: string, // this is the prop type }, { count: number, // this is the state type }> { state = { count: 0 } render() { return (
{this.props.message} {this.state.count}
); } } ``` If you need to define a clickhandler, just do it like normal, but just remember any arguments for your functions also need to be typed: ```tsx class App extends React.Component<{ message: string, }, { count: number, }> { state = { count: 0 } render() { return (
this.increment(1)}>{this.props.message} {this.state.count}
); } increment = (amt: number) => { // like this this.setState({ count: this.state.count + amt }); } } ``` If you need to declare class properties for later use, just declare it with a type: ```tsx class App extends React.Component<{ message: string, }> { pointer: number // like this componentDidMount() { this.pointer = 3; } render() { return (
{this.props.message} and {this.pointer}
); } } ```
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Extracting Prop Types Instead of defining prop types inline, you can declare them separately (useful for reusability or code organization): ```tsx type AppProps = { message: string } const App: React.SFC = ({ message }) =>
{message}
; ``` You can also do this for stateful component types (really, any types): ```tsx type AppProps = { // like this message: string, } type AppState = { // and this count: number, } class App extends React.Component { state = { count: 0 } render() { return (
{this.props.message} {this.state.count}
); } } ``` `interface`s are different from `type`s in Typescript, but for our purposes they do the same things. [read more](https://medium.com/@martin_hotell/interface-vs-type-alias-in-typescript-2-7-2a8f1777af4c)
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Basic Prop Types Examples ```tsx type AppProps = { message: string, count: number, disabled: boolean, names: string[], // array of a type! obj: object, // any object as long as you dont use it in your typescript code obj2: {}, // same object: { id: string, title: string }, // an object with defined properties objects: { id: string, title: string }[], // array of objects! onSomething: Function, // not recommended onClick: () => void, // function that doesn't return anything onChange: (id: number) => void, // function with named prop optional?: OptionalType, // an optional prop } ``` # Useful React Type Examples ```tsx export declare interface AppProps { children1: JSX.Element; // bad children2: JSX.Element | JSX.Element[]; // meh children3: React.ReactChild | React.ReactChildren; // better children: React.ReactNode; // best style?: React.CSSProperties; // for style onChange?: (e: React.FormEvent) => void; // form events! props: Props & React.HTMLProps // to impersonate all the props of a HTML element } ```
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Forms and Events This can be a bit tricky. The 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: ```tsx class App extends React.Component<{}, { // no props text: string, }> { state = { text: '' } render() { return (
); } onChange = (e: React.FormEvent): void => { this.setState({text: e.currentTarget.value}) } } ```
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Higher Order Components/Render Props Sometimes you will want to write a function that can take a React element or a string or something else as a prop. The best Type to use for such a situation is `React.ReactNode` which fits anywhere a normal, well, React Node would fit: ```tsx import * as React from 'react'; export interface Props { label?: React.ReactNode; children: React.ReactNode; } export const Card = (props: Props) => { return (
{props.label &&
{props.label}
} {props.children}
); }; ``` If you are using a function-as-a-child render prop: ```tsx export interface Props { children: (foo: string) => React.ReactNode; } ```
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# References/createRef Use a `React.RefObject`: ```tsx class CssThemeProvider extends React.PureComponent { private rootRef: React.RefObject = React.createRef(); render() { return
{this.props.children}
; } } ```
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Component/Design System Development For developing with Storybook, read the docs I maintain over here: . This includes automatic proptype documentation generation, which is awesome :)
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Building Please contribute on this topic! [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Prettier + TSLint Please contribute on this topic! [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Working with Non-Typescript Libraries (writing your own index.d.ts) Please contribute on this topic! [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
# Troubleshooting Handbook: Types Facing weird type errors? You aren't alone. This is the worst part of using Typescript with React. 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 Union types are handy for solving some of these typing problems: ```tsx class App extends React.Component<{}, { count: number | null, // like this }> { state = { count: null } render() { return (
this.increment(1)}>{this.state.count}
); } increment = (amt: number) => { this.setState({ count: this.state.count + amt }); } } ```
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
## Optional Types If a component has an optional prop, add a question mark :) and assign during destructure (or use defaultProps). ```tsx class MyComponent extends React.Component<{ message?: string, // like this }> { render() { const {message = 'default'} = this.props; return (
{message}
); } } ``` You can also use a `!` character to assert that something is not undefined, but this is not encouraged.
Explanation This is not yet written. Please PR or [File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new) with your suggestions!
## Enum Types Enums in Typescript default to numbers. You will usually want to use them as strings instead: ```tsx export enum ButtonSizes { default = 'default', small = 'small', large = 'large' } ``` Usage: ```tsx export const PrimaryButton = ( props: Props & React.HTMLProps ) => (