👋 This repo is maintained by @swyx and @IslamAttrash, we're so happy you want to try out Typescript with React! This is meant to be an intermediate 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! 👍
Table of Contents
- Prerequisites
- React + Typescript Starter Kits
- Import React
- Stateless Functional Components
- Stateful Class-based Components
- Typing DefaultProps
- Extracting Prop Types
- Basic Prop Types Examples
- Useful React Type Examples
- Forms and Events
- Higher Order Components/Render Props
- References/createRef
- Component/Design System Development
- Building
- Prettier + TSLint
- Working with Non-Typescript Libraries (writing your own index.d.ts)
- Troubleshooting Handbook: Types
- Troubleshooting Handbook: TSLint
- Troubleshooting Handbook: tsconfig.json
- Recommended React + Typescript codebases to learn from
- Other React + Typescript resources
- My question isn't answered here!
Prerequisites
- good understanding of React
- familiarity with Typescript Types
- having read the Typescript section in the official React docs.
- (optional) Read Microsoft's TypeScript-React-Starter docs.
React + Typescript Starter Kits
-
https://github.com/wmonk/create-react-app-typescript is the officially recommended Typescript fork of
create-react-app
.CodeSandbox has a React TypeScript template based on this project.
-
https://github.com/sw-yx/create-react-app-parcel-typescript sets up a React + Typescript app with Parcel :)
-
https://github.com/basarat/typescript-react/tree/master/01%20bootstrap 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.
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 not 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!
Stateless Functional Components
You can specify the type of props as you destructure them:
const App = ({ message }: { message: string }) => <div>{message}</div>;
Or you can use the provided generic type for functional components:
const App: React.SFC<{ message: string }> = ({ message }) => <div>{message}</div>;
Quite frankly I prefer the former pattern as it's shorter.
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Stateful Class-based Components
Within Typescript, React.Component
is a generic type (aka React.Component<PropType, StateType>
), so you actually want to provide it with prop and (optionally) state types:
class App extends React.Component<{
message: string, // it takes one prop called 'message' which is a string type
}> {
render() {
return (
<div>{this.props.message}</div>
);
}
}
If the component has state, here's how to add the types for the state:
class App extends React.Component<{
message: string, // this is the prop type
}, {
count: number, // this is the state type
}> {
state = {
count: 0
}
render() {
return (
<div>{this.props.message} {this.state.count}</div>
);
}
}
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:
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
}));
}
}
If you need to declare class properties for later use, just declare it with a type:
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>
);
}
}
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Typing DefaultProps
It is easy to type defaults for functional components, but there is some debate in the community on how to type the static defaultProps
field for class-based components. We have an active discussion on several approaches on how to do this. Please check out our issue here.
Extracting Prop Types
Instead of defining prop types inline, you can declare them separately (useful for reusability or code organization):
type AppProps = { message: string }
const App: React.SFC<AppProps> = ({ message }) => <div>{message}</div>;
You can also do this for stateful component types (really, any types):
type AppProps = { // like this
message: string,
}
type AppState = { // and this
count: number,
}
class App extends React.Component<AppProps, AppState> {
state = {
count: 0
}
render() {
return (
<div>{this.props.message} {this.state.count}</div>
);
}
}
interface
s are different from type
s in Typescript, but for our purposes they do the same things. read more
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Basic Prop Types Examples
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
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<HTMLInputElement>) => void; // form events!
props: Props & React.HTMLProps<HTMLButtonElement> // to impersonate all the props of a HTML element
}
Explanation
This is not yet written. Please PR or File an issue 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:
class App extends React.Component<{}, { // no props
text: string,
}> {
state = {
text: ''
}
render() {
return (
<div>
<input
type="text"
value={this.state.text}
onChange={this.onChange}
/>
</div>
);
}
onChange = (e: React.FormEvent<HTMLInputElement>): void => {
this.setState({text: e.currentTarget.value})
}
}
Explanation
This is not yet written. Please PR or File an issue 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:
import * as React from 'react';
export interface Props {
label?: React.ReactNode;
children: React.ReactNode;
}
export const Card = (props: Props) => {
return (
<div>
{props.label && <div>{props.label}</div>}
{props.children}
</div>
);
};
If you are using a function-as-a-child render prop:
export interface Props {
children: (foo: string) => React.ReactNode;
}
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
References/createRef
Use a React.RefObject
:
class CssThemeProvider extends React.PureComponent<Props> {
private rootRef: React.RefObject<HTMLDivElement> = React.createRef();
render() {
return <div ref={this.rootRef}>{this.props.children}</div>;
}
}
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Component/Design System Development
For developing with Storybook, read the docs I maintain over here: https://storybook.js.org/configurations/typescript-config/. This includes automatic proptype documentation generation, which is awesome :)
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Building
Please contribute on this topic! File an issue.
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Prettier + TSLint
Please contribute on this topic! File an issue.
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Working with Non-Typescript Libraries (writing your own index.d.ts)
Please contribute on this topic! We have an ongoing issue here with some references.
Explanation
This is not yet written. Please PR or File an issue 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:
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
}));
}
}
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
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.
Explanation
This is not yet written. Please PR or 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, but this doesn't get autocompletion or syntactic benefits:
export declare type Position = 'left' | 'right' | 'top' | 'bottom';
Explanation
This 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:
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}
/>
);
Omit attribute from a type
Sometimes when intersecting types, we want to define our own version of an attribute. For example, I want my component to have a label
, but the type I am intersecting with also has a label
attribute. Here's how to extract that out:
export interface Props {
label: React.ReactNode // this will conflict with the InputElement's label
}
// here is the magic - omitting an attribute
type Diff<T extends string, U extends string> = ({ [P in T]: P } &
{ [P in U]: never } & { [x: string]: never })[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;
// end of magic
// usage
export const Checkbox = (
props: Props & Omit<React.HTMLProps<HTMLInputElement>, 'label'>
) => {
const { label } = props;
return (
<div className='Checkbox'>
<label className='Checkbox-label'>
<input
type="checkbox"
{...props}
/>
</label>
<span>{label}</span>
</div>
);
};
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Type Zoo
As you can see from the Omit example above, you can write significant logic in your types as well. type-zoo is a nice toolkit of operators you may wish to check out (includes Omit).
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
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,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": 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. I like noImplicitAny to force me to type things.
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Recommended React + Typescript codebases to learn from
- https://github.com/jaredpalmer/formik
- https://github.com/jaredpalmer/react-fns
- https://github.com/palantir/blueprint
- https://github.com/Shopify/polaris
Explanation
This is not yet written. Please PR or File an issue with your suggestions!
Other React + Typescript resources
- me! https://twitter.com/swyx
- https://github.com/piotrwitek/react-redux-typescript-guide - HIGHLY HIGHLY RECOMMENDED, i wrote this repo before knowing about this one, this has a lot of stuff I don't cover, including REDUX and JEST.
- Ultimate React Component Patterns with Typescript 2.8
- Basarat's Typescript gitbook has a React section with an Egghead.io course as well.
- Charles Bryant's gitbook 2yrs old and on the more basic side but has sample code and IDE advice.
- You?.