GithubHelp home page GithubHelp logo
react

typescript-cheatsheets / react Goto Github PK

View Code? Open in 1sVSCode Editor NEW
33.7K 387.0 2.8K 2.72 MB

Cheatsheets for experienced React developers getting started with TypeScript

Home Page: https://react-typescript-cheatsheet.netlify.app/

License: MIT License

JavaScript 94.62% CSS 5.38%
typescript typescript-playground reference ts cheatsheet react hacktoberfest

react's Introduction

React+TypeScript Cheatsheets

react + ts logo

Cheatsheets for experienced React developers getting started with TypeScript

Web docs | 中文翻译 | Español | Português | Contribute! | Ask!


👋 This repo is maintained by @swyx, @ferdaber, @eps1lon, @jsjoeio and @arvind-one, we're so happy you want to try out TypeScript with React! If you see anything wrong or missing, please file an issue! 👍


All Contributors | Discord | Tweet

All 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.
  • The Migrating Cheatsheet (/MIGRATING.md) helps 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 (/HOC.md) specifically teaches people to write HOCs with examples.
    • Familiarity with Generics is necessary.
    • ⚠️This is the newest cheatsheet, all assistance is welcome.

Basic Cheatsheet Table of Contents

Expand Table of Contents

Section 1: Setup TypeScript with React

Prerequisites

  1. good understanding of React
  2. familiarity with TypeScript Types (2ality's guide is helpful. If you’re an absolute beginner in TypeScript, check out chibicode’s tutorial.)
  3. having read the TypeScript section in the official React docs.
  4. having read the React section of the new TypeScript playground (optional: also step through the 40+ examples under the playground's Examples section)

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

VS Code Extensions

React + TypeScript Starter Kits

Cloud setups:

Local dev setups:

  • Next.js: npx create-next-app -e with-typescript will create in your current folder
  • Create React App: npx create-react-app name-of-app --template typescript will create in new folder
  • Vite: npm create [email protected] my-react-ts-app -- --template react-ts
  • Meteor: meteor create --typescript name-of-my-new-typescript-app
  • Ignite for React Native: ignite new myapp
  • TSDX: npx tsdx create mylib for Creating React+TS libraries. (in future: TurboRepo)
Other tools

Less mature tools still worth checking out:

Manual setup:

Import React

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

This is the most futureproof way to import React. If you set --allowSyntheticDefaultImports (or add "allowSyntheticDefaultImports": true) in your tsconfig.json you can use more familiar imports:

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

You should also check the new TypeScript docs for official descriptions between each compiler flag!

Video Tutorial

Have a look at the 7-part "React Typescript Course" video series below for an introduction to TypeScript with React.

react typescript course video series

Section 2: Getting Started

Function Components

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

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

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

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

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

Tip: You might use Paul Shen's VS Code Extension to automate the type destructure declaration (incl a keyboard shortcut).

Why is React.FC discouraged? What about React.FunctionComponent/React.VoidFunctionComponent?

You may see this in many React+TypeScript codebases:

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

However, the general consensus today is that React.FunctionComponent (or the shorthand React.FC) is discouraged. This is a nuanced opinion of course, but if you agree and want to remove React.FC from your codebase, you can use this jscodeshift codemod.

Some differences from the "normal function" version:

  • React.FunctionComponent is 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 like displayName, propTypes, and defaultProps.

    • Note that there are some known issues using defaultProps with React.FunctionComponent. See this issue for details. We maintain a separate defaultProps section you can also look up.
  • Before the React 18 type updates, React.FunctionComponent provided an implicit definition of children (see below), which was heavily debated and is one of the reasons React.FC was removed from the Create React App TypeScript template.

// before React 18 types
const Title: React.FunctionComponent<{ title: string }> = ({
  children,
  title,
}) => <div title={title}>{children}</div>;
(Deprecated)Using React.VoidFunctionComponent or React.VFC instead

In @types/react 16.9.48, the React.VoidFunctionComponent or React.VFC type was added for typing children explicitly. However, please be aware that React.VFC and React.VoidFunctionComponent were 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 or React.VFC instead.

type Props = { foo: string };

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

// Error now, in future, deprecated
const VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({
  foo,
  children,
}) => {
  return (
    <div>
      {foo}
      {children}
    </div>
  );
};
  • In the future, it may automatically mark props as readonly, 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 of React.FunctionComponent.

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.

Array.fill

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

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.8 up.

useState

Type inference works very well for simple values:

const [val, toggle] = React.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] = React.useState<IUser | 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] = React.useState<IUser>({} as IUser);

// later...
setUser(newUser);

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

useReducer

You can use Discriminated Unions for reducer actions. Don't forget to define the return type of reducer, otherwise TypeScript will infer it.

const initialState = { count: 0 };

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

function reducer(state: typeof initialState, action: ACTIONTYPE) {
  switch (action.type) {
    case "increment":
      return { count: state.count + action.payload };
    case "decrement":
      return { count: state.count - Number(action.payload) };
    default:
      throw new Error();
  }
}

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

View in the TypeScript Playground

Usage with Reducer from redux

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

So the above reducer example becomes:

import { Reducer } from 'redux';

export function reducer: Reducer<AppState, Action>() {}

useEffect / useLayoutEffect

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

function DelayedEffect(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
  return null;
}
Solution to the above example
function DelayedEffect(props: { timerMs: number }) {
  const { timerMs } = props;

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

useRef

In TypeScript, useRef returns a reference that is either read-only or mutable, 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 use null as initial value. In this case, the returned reference will have a read-only .current that is managed by React. TypeScript expects you to give this ref to an element's ref prop:

function Foo() {
  // - 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>
  const divRef = 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 forgot to assign it
    if (!divRef.current) throw Error("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 <div ref={divRef}>etc</div>;
}

If you are sure that divRef.current will never be null, it is also possible to use the non-null assertion operator !:

const divRef = 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 which HTMLElement to use

Refs demand specificity - it is not enough to just specify any old HTMLElement. If you don't know the name of the element type you need, you can check lib.dom.ts or 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:

function Foo() {
  // Technical-wise, this returns MutableRefObject<number | null>
  const intervalRef = 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 <button onClick={/* clearInterval the ref */}>Cancel timer</button>;
}

See also

useImperativeHandle

We don't have much here, but this is from a discussion in our issues. Please contribute if you have anything to add!

type ListProps<ItemType> = {
  items: ItemType[];
  innerRef?: React.Ref<{ scrollToItem(item: ItemType): void }>;
};

function List<ItemType>(props: ListProps<ItemType>) {
  useImperativeHandle(props.innerRef, () => ({
    scrollToItem() {},
  }));
  return null;
}

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, use TS 3.4 const assertions:

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 const; // 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 are having trouble with const assertions, you can also 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>
  ];
}

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

function tuplify<T extends any[]>(...elements: T) {
  return elements;
}

function useArray() {
  const numberValue = useRef(3).current;
  const functionValue = useRef(() => {}).current;
  return [numberValue, functionValue]; // type is (number | (() => void))[]
}

function useTuple() {
  const numberValue = useRef(3).current;
  const functionValue = useRef(() => {}).current;
  return tuplify(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.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>
    );
  }
}

View in the TypeScript Playground

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,
    }));
  };
}

View in the TypeScript Playground

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>
    );
  }
}

View in the TypeScript Playground

Something to add? File an issue.

Typing getDerivedStateFromProps

Before you start using getDerivedStateFromProps, please go through the documentation and You 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 annotate getDerivedStateFromProps

  1. If you have explicitly typed your derived state and want to make sure that the return value from getDerivedStateFromProps conforms to it.
class Comp extends React.Component<Props, State> {
  static getDerivedStateFromProps(
    props: Props,
    state: State
  ): Partial<State> | null {
    //
  }
}
  1. When you want the function's return value to determine your state.
class Comp extends React.Component<
  Props,
  ReturnType<typeof Comp["getDerivedStateFromProps"]>
> {
  static getDerivedStateFromProps(props: Props) {}
}
  1. When you want derived state with other state fields and memoization
type CustomValue = any;
interface Props {
  propA: CustomValue;
}
interface DefinedState {
  otherStateField: string;
}
type State = DefinedState & ReturnType<typeof transformPropsToState>;
function transformPropsToState(props: Props) {
  return {
    savedPropA: props.propA, // save for memoization
    derivedState: props.propA,
  };
}
class Comp extends React.PureComponent<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      otherStateField: "123",
      ...transformPropsToState(props),
    };
  }
  static getDerivedStateFromProps(props: Props, state: State) {
    if (isEqual(props.propA, state.savedPropA)) return null;
    return transformPropsToState(props);
  }
}

View in the TypeScript Playground

You May Not Need defaultProps

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

The consensus is to use object default values.

Function Components:

type GreetProps = { age?: number };

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

Class Components:

type GreetProps = {
  age?: number;
};

class Greet extends React.Component<GreetProps> {
  render() {
    const { age = 21 } = this.props;
    /*...*/
  }
}

let el = <Greet age={3} />;

Typing defaultProps

Type inference improved greatly for defaultProps in TypeScript 3.0+, although some 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.com/typescript-cheatsheets/react/issues/415#issuecomment-841223219
type GreetProps = { age: number } & typeof defaultProps;

const defaultProps = {
  age: 21,
};

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

See this in TS Playground

For Class components, there are a couple ways to do it (including using the Pick utility type) but the recommendation is to "reverse" the props definition:

type GreetProps = typeof Greet.defaultProps & {
  age: number;
};

class Greet extends React.Component<GreetProps> {
  static defaultProps = {
    age: 21,
  };
  /*...*/
}

// Type-checks! No type assertions needed!
let el = <Greet age={3} />;
JSX.LibraryManagedAttributes nuance for library authors

The above implementations work fine for App creators, but sometimes you want to be able to export GreetProps so that others can consume it. The problem here is that the way GreetProps is defined, age is a required prop when it isn't because of defaultProps.

The insight to have here is that GreetProps is the internal contract for your component, not the external, consumer facing contract. You could create a separate type specifically for export, or you could make use of the JSX.LibraryManagedAttributes utility:

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

class Greet extends Component<GreetProps> {
  static defaultProps = { age: 21 };
}

// external contract
export type ApparentGreetProps = JSX.LibraryManagedAttributes<
  typeof Greet,
  GreetProps
>;

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

Consuming Props of a Component with defaultProps

A component with defaultProps may seem to have some required props that actually aren't.

Problem Statement

Here's what you want to do:

interface IProps {
  name: string;
}
const defaultProps = {
  age: 25,
};
const GreetComponent = ({ name, age }: IProps & typeof defaultProps) => (
  <div>{`Hello, my name is ${name}, ${age}`}</div>
);
GreetComponent.defaultProps = defaultProps;

const TestComponent = (props: React.ComponentProps<typeof GreetComponent>) => {
  return <h1 />;
};

// Property 'age' is missing in type '{ name: string; }' but required in type '{ age: number; }'
const el = <TestComponent name="foo" />;

Solution

Define a utility that applies JSX.LibraryManagedAttributes:

type ComponentProps<T> = T extends
  | React.ComponentType<infer P>
  | React.Component<infer P>
  ? JSX.LibraryManagedAttributes<T, P>
  : never;

const TestComponent = (props: ComponentProps<typeof GreetComponent>) => {
  return <h1 />;
};

// No error
const el = <TestComponent name="foo" />;

See this in TS Playground

Misc Discussions and Knowledge

Why does React.FC break defaultProps?

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:

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 and here.

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:

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 but useful as placeholder) */
  obj: object;
  obj2: {}; // almost the same as `object`, exactly the same as `Object`
  /** an object with any number of properties (PREFERRED) */
  obj3: {
    id: string;
    title: string;
  };
  /** array of objects! (common) */
  objArr: {
    id: string;
    title: string;
  }[];
  /** a dict object with any number of properties of the same type */
  dict1: {
    [key: string]: MyTypeHere;
  };
  dict2: Record<string, MyTypeHere>; // equivalent to dict1
  /** 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;
  /** 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;
  /** 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

Relevant for components that accept other React components as props.

export declare interface AppProps {
  children1: JSX.Element; // bad, doesnt account for arrays
  children2: JSX.Element | JSX.Element[]; // meh, doesn't accept strings
  children3: React.ReactChildren; // despite the name, not at all an appropriate type; it is a utility
  children4: React.ReactChild[]; // better, accepts array children
  children: React.ReactNode; // best, accepts everything (see edge case below)
  functionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop type
  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
}
Small React.ReactNode edge case

This code typechecks but has a runtime error:

type Props = {
  children: React.ReactNode;
};

function Comp({ children }: Props) {
  return <div>{children}</div>;
}
function App() {
  return <Comp>{{}}</Comp>; // Runtime Error: Objects not valid as React Child!
}

This is because ReactNode includes ReactFragment which allows a {} type, which is too wide. Fixing this would break a lot of libraries, so for now you just have to be mindful that ReactNode is not absolutely bulletproof.

Thanks @pomle for raising this.

With the React 18 type updates, {} is no longer allowed in ReactFragment.

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

More discussion: Where ReactNode does not overlap with 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 use interface for public API's definition when authoring a library or 3rd party ambient type definitions, as this allows a consumer to extend them via declaration merging if some definitions are missing.

  • consider using type for 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 in Interface vs Type alias in TypeScript 2.7.

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

Note: At scale, there are performance reasons to prefer interfaces (see official Microsoft notes on this) but take 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 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 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 using getDerivedStateFromProps, please go through the documentation and You 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 annotate getDerivedStateFromProps

  1. If you have explicitly typed your derived state and want to make sure that the return value from getDerivedStateFromProps conforms to it.
class Comp extends React.Component<Props, State> {
  static getDerivedStateFromProps(
    props: Props,
    state: State
  ): Partial<State> | null {
    //
  }
}
  1. When you want the function's return value to determine your state.
class Comp extends React.Component<
  Props,
  ReturnType<typeof Comp["getDerivedStateFromProps"]>
> {
  static getDerivedStateFromProps(props: Props) {}
}
  1. When you want derived state with other state fields and memoization
type CustomValue = any;
interface Props {
  propA: CustomValue;
}
interface DefinedState {
  otherStateField: string;
}
type State = DefinedState & ReturnType<typeof transformPropsToState>;
function transformPropsToState(props: Props) {
  return {
    savedPropA: props.propA, // save for memoization
    derivedState: props.propA,
  };
}
class Comp extends React.PureComponent<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      otherStateField: "123",
      ...transformPropsToState(props),
    };
  }
  static getDerivedStateFromProps(props: Props, state: State) {
    if (isEqual(props.propA, state.savedPropA)) return null;
    return transformPropsToState(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 use type inference and contextual typing:

const el = (
  <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 an onChange for a form event:

type State = {
  text: string;
};
class App extends React.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>
        <input type="text" value={this.state.text} onChange={this.onChange} />
      </div>
    );
  }
}

View in the TypeScript Playground

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.

Typing onSubmit, with Uncontrolled components in a Form

If you don't quite care about the type of the event, you can just use React.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();
    const target = e.target as typeof e.target & {
      email: { value: string };
      password: { value: string };
    };
    const email = target.email.value; // typechecks!
    const password = target.password.value; // typechecks!
    // etc...
  }}
>
  <div>
    <label>
      Email:
      <input type="email" name="email" />
    </label>
  </div>
  <div>
    <label>
      Password:
      <input type="password" name="password" />
    </label>
  </div>
  <div>
    <input type="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 Formik or React 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: wheel event should not be confused with the scroll event)
SyntheticEvent The base event for all above events. Should be used when unsure about event type
What about InputEvent?

You've probably noticed that there is no InputEvent. 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 use KeyboardEvent instead.

Sources:

Context

Basic Example

import * as React from "react";

interface AppContextInterface {
  name: string;
  author: string;
  url: string;
}

const AppCtx = React.createContext<AppContextInterface | null>(null);

// Provider in your app

const sampleAppContext: AppContextInterface = {
  name: "Using React Context in a Typescript App",
  author: "thehappybug",
  url: "http://www.example.com",
};

export const App = () => (
  <AppCtx.Provider value={sampleAppContext}>...</AppCtx.Provider>
);

// Consume in your app

export const PostInfo = () => {
  const appContext = React.useContext(AppCtx);
  return (
    <div>
      Name: {appContext.name}, Author: {appContext.author}, Url:{" "}
      {appContext.url}
    </div>
  );
};

You can also use the Class.contextType or Context.Consumer API, let us know if you have trouble with that.

Thanks to @AlvSovereign

Extended Example

Using React.createContext with an empty object as default value.

interface ContextState {
  // set the type of state you want to handle with context e.g.
  name: string | null;
}
//set an empty object as default state
const Context = React.createContext({} as ContextState);
// set up context provider as you normally would in JavaScript [React Context API](https://reactjs.org/docs/context.html#api)

Using React.createContext and context getters to make a createCtx with no defaultValue, yet no need to check for undefined:

import * as React from "react";

const currentUserContext = React.createContext<string | undefined>(undefined);

function EnthusasticGreeting() {
  const currentUser = React.useContext(currentUserContext);
  return <div>HELLO {currentUser!.toUpperCase()}!</div>;
}

function App() {
  return (
    <currentUserContext.Provider value="Anders">
      <EnthusasticGreeting />
    </currentUserContext.Provider>
  );
}

Notice the explicit type arguments which we need because we don't have a default string value:

const currentUserContext = React.createContext<string | undefined>(undefined);
//                                             ^^^^^^^^^^^^^^^^^^

along with the non-null assertion to tell TypeScript that currentUser is definitely going to be there:

return <div>HELLO {currentUser!.toUpperCase()}!</div>;
//                              ^

This is unfortunate because we know that later in our app, a Provider is going to fill in the context.

There are a few solutions for this:

  1. You can get around this by asserting non null:

    const currentUserContext = React.createContext<string>(undefined!);

    (Playground here) This is a quick and easy fix, but this loses type-safety, and if you forget to supply a value to the Provider, you will get an error.

  2. We can write a helper function called createCtx that guards against accessing a Context whose value wasn't provided. By doing this, API instead, we never have to provide a default and never have to check for undefined:

    import * as React from "react";
    
    /**
     * A helper to create a Context and Provider with no upfront default value, and
     * without having to check for undefined all the time.
     */
    function createCtx<A extends {} | null>() {
      const ctx = React.createContext<A | undefined>(undefined);
      function useCtx() {
        const c = React.useContext(ctx);
        if (c === undefined)
          throw new Error("useCtx must be inside a Provider with a value");
        return c;
      }
      return [useCtx, ctx.Provider] as const; // 'as const' makes TypeScript infer a tuple
    }
    
    // Usage:
    
    // We still have to specify a type, but no default!
    export const [useCurrentUserName, CurrentUserProvider] = createCtx<string>();
    
    function EnthusasticGreeting() {
      const currentUser = useCurrentUserName();
      return <div>HELLO {currentUser.toUpperCase()}!</div>;
    }
    
    function App() {
      return (
        <CurrentUserProvider value="Anders">
          <EnthusasticGreeting />
        </CurrentUserProvider>
      );
    }

    View in the TypeScript Playground

  3. You can go even further and combine this idea using React.createContext and context getters.

    /**
     * A helper to create a Context and Provider with no upfront default value, and
     * without having to check for undefined all the time.
     */
    function createCtx<A extends {} | null>() {
      const ctx = React.createContext<A | undefined>(undefined);
      function useCtx() {
        const c = React.useContext(ctx);
        if (c === undefined)
          throw new Error("useCtx must be inside a Provider with a value");
        return c;
      }
      return [useCtx, ctx.Provider] as const; // 'as const' makes TypeScript infer a tuple
    }
    
    // usage
    
    export const [useCtx, SettingProvider] = createCtx<string>(); // specify type, but no need to specify value upfront!
    export function App() {
      const key = useCustomHook("key"); // get a value from a hook, must be in a component
      return (
        <SettingProvider value={key}>
          <Component />
        </SettingProvider>
      );
    }
    export function Component() {
      const key = useCtx(); // can still use without null check!
      return <div>{key}</div>;
    }

    View in the TypeScript Playground

  4. Using React.createContext and useContext to make a createCtx with unstated-like context setters:

    export function createCtx<A>(defaultValue: A) {
      type UpdateType = React.Dispatch<
        React.SetStateAction<typeof defaultValue>
      >;
      const defaultUpdate: UpdateType = () => defaultValue;
      const ctx = React.createContext({
        state: defaultValue,
        update: defaultUpdate,
      });
      function Provider(props: React.PropsWithChildren<{}>) {
        const [state, update] = React.useState(defaultValue);
        return <ctx.Provider value={{ state, update }} {...props} />;
      }
      return [ctx, Provider] as const; // alternatively, [typeof ctx, typeof Provider]
    }
    
    // usage
    
    const [ctx, TextProvider] = createCtx("someText");
    export const TextContext = ctx;
    export function App() {
      return (
        <TextProvider>
          <Component />
        </TextProvider>
      );
    }
    export function Component() {
      const { state, update } = React.useContext(TextContext);
      return (
        <label>
          {state}
          <input type="text" onChange={(e) => update(e.target.value)} />
        </label>
      );
    }

    View in the TypeScript Playground

  5. A useReducer-based version may also be helpful.

Mutable Context Using a Class component wrapper

Contributed by: @jpavon

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

Check the Hooks section for useRef.

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>
));
Side note: the ref you get from forwardRef is mutable so you can assign to it if needed.

This was done on purpose. You can make it immutable if you have to - assign React.Ref if you want to ensure nobody reassigns it:

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

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

Generic forwardRefs

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

Option 1 - Wrapper component

type ClickableListProps<T> = {
  items: T[];
  onSelect: (item: T) => void;
  mRef?: React.Ref<HTMLUListElement> | null;
};

export function ClickableList<T>(props: ClickableListProps<T>) {
  return (
    <ul ref={props.mRef}>
      {props.items.map((item, i) => (
        <li key={i}>
          <button onClick={(el) => props.onSelect(item)}>Select</button>
          {item}
        </li>
      ))}
    </ul>
  );
}

Option 2 - Redeclare forwardRef

// Redecalare forwardRef
declare module "react" {
  function forwardRef<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!

type ClickableListProps<T> = {
  items: T[];
  onSelect: (item: T) => void;
};
function ClickableListInner<T>(
  props: ClickableListProps<T>,
  ref: React.ForwardedRef<HTMLUListElement>
) {
  return (
    <ul ref={ref}>
      {props.items.map((item, i) => (
        <li key={i}>
          <button onClick={(el) => props.onSelect(item)}>Select</button>
          {item}
        </li>
      ))}
    </ul>
  );
}

export const ClickableList = React.forwardRef(ClickableListInner);

More Info

You may also wish to do Conditional Rendering with forwardRef.

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);
  }
}

View in the TypeScript Playground

Using hooks

Same as above but using hooks

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

const modalRoot = document.querySelector("#modal-root") as HTMLElement;

const Modal: React.FC<{}> = ({ children }) => {
  const el = useRef(document.createElement("div"));

  useEffect(() => {
    // Use this in case CRA throws an error about react-hooks/exhaustive-deps
    const current = el.current;

    // We assume `modalRoot` exists with '!'
    modalRoot!.appendChild(current);
    return () => void modalRoot!.removeChild(current);
  }, []);

  return createPortal(children, el.current);
};

export default Modal;

View in the TypeScript Playground

Modal Component Usage Example:

function App() {
  const [showModal, setShowModal] = React.useState(false);
  return (
    <div>
      // you can also put this in your static html file
      <div id="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>
      )}
      <button onClick={() => setShowModal(true)}>show Modal</button>
      // rest of your app
    </div>
  );
}
Context of Example

This example is based on the Event Bubbling Through Portal example 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.

Options 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 own ErrorBoundary component.

import React, { Component, ErrorInfo, ReactNode } from "react";

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
}

class ErrorBoundary extends Component<Props, State> {
  public state: State = {
    hasError: false
  };

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

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

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

    return this.props.children;
  }
}

export default ErrorBoundary;

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.

Troubleshooting Handbook: Types

⚠️ Have you read the TypeScript FAQ Your 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 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,
    }));
  };
}

View in the TypeScript Playground

Type Guarding: Sometimes Union Types solve a problem in one area but create another downstream. If A and B are both object types, A | B isn'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:

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

// Method 1: use `in` keyword
function redirect(user: Admin | User) {
  if ("role" in user) {
    // 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
function isAdmin(user: Admin | User): user is Admin {
  return (user as any).role !== undefined;
}

View in the TypeScript Playground

Method 2 is also known as User-Defined Type Guards and can be really handy for readable code. This is how TS itself refines types with typeof and instanceof.

If you need if...else 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

We recommend avoiding using enums as far as possible.

Enums have a few documented issues (the TS team agrees). A simpler alternative to enums is just declaring a union type of string literals:

export declare type Position = "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:

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

// usage
export const PrimaryButton = (
  props: Props & React.HTMLProps<HTMLButtonElement>
) => <Button size={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 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>
    );
  }
}

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
let userID!: 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 with type branding:

type OrderID = string & { readonly brand: unique symbol };
type UserID = string & { readonly brand: unique symbol };
type ID = OrderID | UserID;

We can create these values with the Companion Object Pattern:

function OrderID(id: string) {
  return id as OrderID;
}
function UserID(id: string) {
  return id as UserID;
}

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

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

In future you can use the unique keyword 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 a button:

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

Playground here

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

type BaseProps = {
   className?: string,
   style?: React.CSSProperties
   name: string // used in both
}
type DogProps = {
  tailsCount: number
}
type HumanProps = {
  handsCount: number
}
export const Human: React.FC<BaseProps & HumanProps> = // ...
export const Dog: React.FC<BaseProps & DogProps> = // ...

View in the TypeScript Playground

Make sure not to confuse Intersection Types (which are and operations) with Union Types (which are or operations).

Union Types

This section is yet to be written (please contribute!). Meanwhile, see our commentary 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:

type FunctionType1 = (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:

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

However, if you don't have an implementation and are just writing a .d.ts definition 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:

type pickCard = {
  (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, 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 React.ComponentProps and typeof, and optionally Omit any overlapping types
import { Button } from "library"; // but doesn't export ButtonProps! oh no!
type ButtonProps = React.ComponentProps<typeof Button>; // no problem! grab your own!
type AlertButtonProps = Omit<ButtonProps, "onClick">; // modify
const AlertButton: React.FC<AlertButtonProps> = (props) => (
  <Button onClick={() => alert("hello")} {...props} />
);

You may also use ComponentPropsWithoutRef (instead of ComponentProps) and ComponentPropsWithRef (if your component specifically forwards refs)

  • 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 }

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

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

type InstType = ReturnType<typeof foo>;
type SubInstArr = InstType["subInstArr"];
type SubInstType = SubInstArr[0];

let baz: 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)
type SubInstType2 = ReturnType<typeof foo>["subInstArr"][0];
let baz2: SubInstType2 = {
  c: 5,
  d: 6, // type checks ok!
};
  • TS also ships with a Parameters utility type for extracting the parameters of a function
  • for anything more "custom", the infer keyword 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, and this example to get the idea. Basarat also has a good video on infer.

The Types I need don't exist!

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

Before you proceed - make sure you have checked that types don't exist in DefinitelyTyped or TypeSearch

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

Slapping any on everything

A lazier way would be to create a new type declaration file, say typedec.d.ts– if you don't already have one. Ensure that the path to file is resolvable by TypeScript by checking the include array in the tsconfig.json file 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 the declare syntax for your desired module, say my-untyped-module– to the declaration file:

// inside typedec.d.ts
declare module "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 the Any type 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 --allowJs and --declaration to see TypeScript's "best guess" at the types of the library.

If this doesn't work well enough, use dts-gen to 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 - see our 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 an index.js file. Typically you need a minimum of two type declarations (one for Input Prop and the other for Return Prop) to define a hook completely. Suppose the hook you wish to type follows the following structure,
// ...
const useUntypedHook = (prop) => {
  // some processing happens here
  return {
    /* ReturnProps */
  };
};
export default useUntypedHook;

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

declare module 'use-untyped-hook' {
  export interface InputProps { ... }   // type declaration for prop
  export interface ReturnProps { ... } // type declaration for return props
  export default function useUntypedHook(
    prop: InputProps
    // ...
  ): ReturnProps;
}
For instance, the useDarkMode hook exports the functions that follows a similar structure.
// inside src/index.js
const useDarkMode = (
  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]),
  };
};
export default useDarkMode;

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

declare module "use-dark-mode" {
  /**
   * A config object allowing you to specify certain aspects of `useDarkMode`
   */
  export interface DarkModeConfig {
    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`.
   */
  export interface DarkMode {
    readonly value: boolean;
    enable: () => void;
    disable: () => void;
    toggle: () => void;
  }
  /**
   * A custom React Hook to help you implement a "dark mode" component for your application.
   */
  export default function useDarkMode(
    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 using class UntypedClassComponent extends React.Component<UntypedClassComponentProps, any> {} where UntypedClassComponentProps holds the type declaration.

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

declare module "react-router-dom" {
  import * as React from 'react';
  // ...
  type NavigateProps<T> = {
    to: string | number,
    replace?: boolean,
    state?: T
  }
  //...
  export class Navigate<T = any> extends React.Component<NavigateProps<T>>{}
  // ...

For more information on creating type definitions for class components, you can refer to this post for 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.com/tannerlinsley/status/1390409931627499523. see also microsoft/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.com/ryanflorence/status/1085745787982700544?s=20

Troubleshooting Handbook: Operators

  • typeof and instanceof: type query used for refinement
  • keyof: get keys of an object. keyof T is an operator to tell you what values of k can be used for obj[k].
  • O[K]: property lookup
  • [K in O]: mapped types
  • + or - or readonly or ?: 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:

  • 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 a newing a class constructor
  • NonNullable: exclude null and undefined from a 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

Troubleshooting Handbook: tsconfig.json

You can find all 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 in tsdx):

{
  "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 more recommended 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: 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.
  • "typeRoots": ["./typings", "./node_modules/@types"]: By default, TypeScript looks in node_modules/@types and 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 special typings folder.

Compilation speed grows linearly with size of codebase. For large projects, you will want to use Project References. See our ADVANCED cheatsheet for commentary.

Troubleshooting Handbook: Fixing 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";

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

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

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

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

You can also do ambient variable and ambient type declarations:

// ambient utiltity type
type ToArray<T> = T extends unknown[] ? T : T[];
// ambient variable
declare let process: {
  env: {
    NODE_ENV: "development" | "production";
  };
};
process = {
  env: {
    NODE_ENV: "production",
  },
};

You can see examples of these included in the built in type declarations in the lib field of tsconfig.json

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:

Other React + TypeScript resources

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 that TSLint 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-parser is no longer maintained and work has recently begun on typescript-eslint in the ESLint community to bring ESLint up to full parity and interop with TSLint.

Follow the TypeScript + ESLint docs at https://github.com/typescript-eslint/typescript-eslint:

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

add a lint script to your package.json:

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

and a suitable .eslintrc.js (using .js over .json here 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 from the tsdx PR which is for libraries.

More .eslintrc.json options to consider with more options you may want for apps:

{
  "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"
      }
    }
  ]
}

You can read a fuller TypeScript + ESLint setup guide here from Matterhorn, in particular check https://github.com/MatterhornDev/learn-typescript-linting.

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

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

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

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 the all-contributors specification. See CONTRIBUTORS.md for the full list. Contributions of any kind welcome!

react's People

Contributors

sw-yx avatar github-actions[bot] avatar allcontributors[bot] avatar eps1lon avatar tsiq-swyx avatar isarvindone avatar jsjoeio avatar Attrash-Islam avatar ferdaber avatar filiptammergard avatar azizhk avatar ryota-murakami avatar dependabot[bot] avatar orta avatar jpavon avatar azdanov avatar elit-altum avatar dance2die avatar gnbaron avatar mjsarfatti avatar tpetrina avatar charrondev avatar quassnoi avatar dwjohnston avatar ledenis avatar david-szabo97 avatar Winner95 avatar jxom avatar kripod avatar MenaiAla avatar

Stargazers

David Gonzalez avatar Guilherme G. Bellotti avatar Nina Armangué Braun avatar Omurbek avatar  avatar  avatar GOPIKRISHNAN B avatar xxibcill avatar Serge Ivlev avatar harshavardhanpb avatar Giovanni Mendes Mansueto avatar  avatar Shuja Zafar avatar Alfian Ananda Putra avatar  avatar roottool avatar haiyanLuo avatar DenisRaymer avatar Bipin Parajuli avatar Ji ZHANG avatar Akman avatar David Lannoye avatar Timothy Brits avatar dataneo avatar murtaza avatar MahdiMurshed avatar Craig Edney avatar Lucía Brumnich avatar Francisco Vivas avatar Ez avatar Andrés Menchaca avatar  avatar Nickan avatar Imran Hussain avatar  avatar Robert Xu avatar Basit Afridi avatar  avatar Rasul avatar ErickO avatar  avatar Chunghee Kim avatar Ryan Fernando avatar Derek Yu avatar Adrian Beria avatar Mirek Sivák avatar Iulian Carnaru avatar  avatar Shubham Gore avatar DevEnock avatar Fernando Adan Figueroa Abarca avatar Jhoan Stiven Zamora avatar Andrew Wong avatar Christopher Ward avatar Caio Luiz avatar  avatar  avatar Spencer McKenney avatar Kingvin avatar Zülal Nebin avatar  avatar  avatar Yu Hien avatar  avatar Oliver avatar 十六夜 avatar  avatar Lee Morrow avatar Mau avatar  avatar 透露 avatar Yuwei Zhao avatar Jorge Silva avatar Mike Lee avatar Samuel Robertson avatar Isaah avatar Raymond Poon avatar Vaibhav Muchandi avatar C.M.R.A avatar Marco Steinke avatar mitanshu avatar Oguntade Abass avatar DAM avatar  avatar Carlos Alejandro Hernández Mejía avatar Jeong Ha Seung avatar Patrick Luz avatar _XiaoTian avatar  avatar Vincent Ngian avatar Erica Carvalho avatar 溫酒 avatar Lcy avatar  avatar  avatar Ankit Kanyal avatar Vicki Cheung avatar Ticiano avatar Daniel  avatar  avatar

Watchers

Jeff Morin avatar Piotr Kapera avatar Kohei Hasegawa avatar Lưu Trọng Hiếu avatar Michał Świtoń avatar Bryan Migliorisi avatar Orta Therox avatar Aarron Painter avatar German Blejman avatar Steven Black avatar rukos avatar Franklin Chen avatar vancaem avatar Adrian Lawrence avatar Daniel Pfefferkorn avatar harmy avatar Joshua Clanton avatar Carlos Villuendas Zambrana avatar Muescha avatar Ed Panameno avatar Alan Garcia avatar Imre Osswald avatar Johno Scott avatar Fawad Niazi avatar Sendy Putra avatar A'braham Barakhyahu avatar Richard Hess avatar Brian Olson avatar Juan Salvador Aleixandre avatar Stéphane Le Dorze avatar Kevin Coyner avatar Elving Rodríguez avatar Martin Galpin avatar Osvaldo avatar Andrey Starostin avatar Ricky Souza avatar  avatar James Cloos avatar koji avatar Steve Lilley avatar kyle avatar Saint Clair avatar  avatar Mitchell Seaton avatar aurimas avatar Krister Kari avatar George Koutsikos avatar Kuba Florczuk avatar Isaac Huang avatar Rafael Crispim Ignácio avatar Jesse avatar Raúl López avatar zhangaz1 avatar Bonggyun Lee avatar yun.kou avatar Laércio de Sousa avatar Thinh Phan avatar kimura-kazunori avatar Lukáš Dvořák avatar Toni Petrina avatar Damola A avatar Camilo avatar Oscar Bicada III avatar Julio Pavón avatar  avatar Tuan Nguyen Minh avatar Dominic Busby avatar saasfreelancer avatar Aleš Vojta avatar Christian Lehner avatar Tony Brown avatar 海勋 avatar  avatar Thilak Rao avatar Somasundaram Ayyappan avatar Vijay Dev avatar  avatar Dennison Bertram avatar Yuriy Evdokimov avatar dale tan avatar Vitalie Glodeanu avatar Yu Hoshino avatar Christian Bican avatar Sebastian Tabares Amaya avatar Florin Cosmin avatar Timo Santi avatar Muly Oved avatar derese.getachew avatar  avatar 狼叔 avatar Luke avatar Alem avatar  avatar Emmanuel Haguet avatar Andrii Pavliuk avatar Dennis Pitallano avatar Laurent Chean avatar toby avatar Skylar Kong avatar Mike Klein avatar

react's Issues

State annotation inside the constructor

##If you have to initial your state inside the constructor, is it also recommended to add second annotation outside the constructor? something like:

class MyComponent extend<IProps, IState> {
    state: IState
    constructor (props: IProps) {
        super(props)
        this.setState({ name: props.name})
    }
}

P.S. Thanks for your awesome guideline ❤️❤️❤️

[Basic] Add coc.vim to tools section

What cheatsheet is this about? (if applicable)

Basic cheatsheet

What's your issue or idea?

I would like to add https://github.com/neoclide/coc.nvim to the tools section for vim. It's insanely powerful and is on its way to replicating VSCode level of integration for Vim.

Will send a PR with this change if you're up for it.

Context - Provider & Consumer should be a pair

Context shows how to create a provider but doesn't provide a way to use the Consumer.

What do you think about providing a code snippet for the consumer as well?

I can do a PR for the code snippet that shows how to consume using Consumer

Edit jlqo76kxov

import * as React from "react";
import { render } from "react-dom";
import { Provider, Consumer, ProviderStore } from "./components/Provider.tsx";

const App = () => (
  <div style={styles}>
    <Provider>
      <Consumer>
        {(store: ProviderStore) => (
          <div>
            <span>Theme Color: </span>
            <p style={{ color: store.state.themeColor }}>
              {store.state.themeColor}
            </p>
          </div>
        )}
      </Consumer>
    </Provider>
  </div>
);

render(<App />, document.getElementById("root"));

How to describe type of props for children

// item is of PageItem type

const controls = _.map(items, item => <FVDesignerItem key={item.id} item={item} />);
        return (
            <FvPageWrapper>
                <FvPositioningContainer disabled={disabled}>{controls}</FvPositioningContainer>
            </FvPageWrapper>
        );

...
// FvPositioningContainer .tsx

React.Children.map(children, (child, i) => {
            if (!child) return undefined;
            const { x, y, w, h } = child.props.item;  // item here is of PageItem , propagated automatically and validated by tsc
           ....
        });

[Long Term Plan] Move to docusaurus

thanks to many people's contributions the cheatsheet is starting to get long, and im starting to think about how to scale this thing. i think FB's docusaurus is a good way to maintain readable and searchable react+typescript docs, while still allowing us to edit markdown easily.

the other big wishlist item i have is to note down the specific version features of Typescript that have particular significance or application in React. There will be a lot coming down with 3.0 but its hard for me to keep track with what happened since 2.0. a series of sections on each TS version would be an interesting an idea and allows people to learn cumulatively or starting from whatever base of knowledge they have.

FunctionComponent and ComponentClass are not compatible with LibraryManagedAttributes

Annotating functions and classes with FunctionComponent and ComponentClass breaks LibraryManagedAttributes due to the static defaultProps property on those interfaces being set to optional.

import { FunctionComponent, ComponentClass, Component } from 'react'

export interface Props {
  foo: string
  bar?: boolean
}

const TestFunction: FunctionComponent<Props> = props => <div />
TestFunction.defaultProps = {
  foo: '',
}

const TestClass: ComponentClass<Props> = class TestClass extends Component<Props> {
  static defaultProps = {
    foo: '',
  }

  render() {
    return <div />
  }
}

// type is never
type TestDefaultProps = typeof TestFunction extends { defaultProps: infer D } ? D : never
type TestClassDefaultProps = typeof TestClass extends { defaultProps: infer D } ? D : never

// type is Props because typeof Test does not extend { defaultProps } but rather { defaultProps? }
type TestManagedProps = JSX.LibraryManagedAttributes<typeof TestFunction, Props>
type TestClassManagedProps = JSX.LibraryManagedAttributes<typeof TestClass, Props>

This causes defaultProps to be completely ignored by JSX.LibraryManagedAttributes. We should probably remove it as a recommendation from the cheat sheet for now.

Please add a workaround for Redux demo in Prerequisite 4

🤔 What?

Redux demo in 4. (optional) Read Microsoft's TypeScript-React-Starter docs fails to work as README is out of date.

  1. Failure 1
    Creating a store section - fix in Pull Request.

  2. Failure 2
    Making a container section - Fix in Pull Request.

For the demo program in TypeScript-React-Starter Redux demo to work, either

  1. PR needs to be merged
  2. or need to update the demo manually according to the changes as mentioned above.

🚀 Suggestion

Please provide users a heads-up when proceeding to go over the prerequisite 4 (optional) Read Microsoft's TypeScript-React-Starter docs.

[Basic] ESLint complains about missing return type in React.FunctionComponent

Please see the following:

const CoolComponent: React.FunctionComponent<{}> = () => (
  <Fragment>
    CoolComponent
  </Fragment>
);

export default CoolComponent;

ESLint says: warning: Missing return type on function

Were the following:

const CoolComponent: React.FunctionComponent<{}> = (): ReactElement => (
  <Fragment>
    CoolComponent
  </Fragment>
);

export default CoolComponent;

Fixes the warning.

What do you think? What is the better code?

Prettier + TSLint + ESLint

I have been playing around with this idea for some time. Why? I miss some of the plugins and functionality of eslint in typescript (ay11, import, airbnb, unicorn with some other plugins and configs.)

Here's my gist with settings: https://gist.github.com/azdanov/7e74ed6ce41536b08277f4121a4f5218

And a working repo:
https://github.com/azdanov/tslint-eslint-crats

What is important:

Issues:

Add example of dynamic HTML tags

Trying to find the "right" @types/react in the advance cheatsheet to use for dynamic HTML tag props. I'm struggling to find the right way of writing this in TS:

import React from "react";

type Props = {
  is?:
    | "h1"
    | "h2"
    | "h3"
    | "h4"
    | "h5"
    | "h6";
  children: React.ReactNode;
};

const Text = ({ is: Element, children }: Props) => (
  <Element>{children}</Element>
);

Text.defaultProps = {
  is: "span"
};

This produces the TS error: JSX element type 'Element' does not have any construct or call signatures

Based on the advanced docs, I've tried writing the is? type as :

  • JSX.InstrinsicElements<"h1"|"h2">
  • React.ReactElement<"h1"|"h2">
  • React.ElementType<"h1"|"h2">

But this isn't working. Any help is much appreciated!

typescript 怎么在可选属性上定义默认值

我想在可选属性上设置默认值,但是又不想在render 里给value 设默认值

const { value =5} = this.props

我找了很多方法,Partial也不行,以下是我代码
image
image
错误如下
image

import * as React from "react";

class App extends React.Component {
  public render() {
    return <A test={"a"} />;
  }
}

type AProps = {
  value?: number;
  [propName: string]: any;
};

class A extends React.Component<AProps, any> {
  static defaultProps = {
    value: 5,
  };
  public render() {
    const { value } = this.props;

    return <B value={value} />;
  }
}

type BProps = {
  value: number;
};
class B extends React.Component<BProps, any> {
  public render() {
    const { value } = this.props;

    return <div>{value}</div>;
  }
}

typo in Section 2: Getting Started example

In Section 2: Getting Started > What's the difference?

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

Should probably be:

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

How best to document the setup, dev, and build process?

if I write too much I end up writing a typescript textbook. I would really like to avoid that. but sometimes there are little shitty issues when setting up and building a react+ typescript app. should I just have a separate BUILDING.md?

Typing for Context API where Context defaultValue is `null`

Hi there

There are times where we want the defaultValue for React's Context API to be null.

I've found this solution.

TLDR:

import * as React from 'react';

interface AppContextInterface {
  name: string,
  author: string,
  url: string
}

const {Provider, Consumer} = React.createContext<AppContextInterface | null>(null);

Now we can pass null in as a default value as our React.createContext argument.

awesome advice from Ferdaber

Hi! I'm one of the contributors/maintainers to the @react/types library in DT, and I just have some suggested changes to the docs to ensure that folks who start with TS in React has a smoother experience!

For the section on Function Components:

  • A common pitfall is that these patterns are not supported:
const MyConditionalComponent = ({ shouldRender = false }) => shouldRender ? <div /> : false
const MyArrayComponent = () => Array(5).fill(<div />)
const el = <MyConditionalComponent /> // throws an error
const el2 = <MyArrayComponentt /> // 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. 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

For the section on Class Components:

  • I recommend annotating the state class property in addition to adding it as the 2nd generic type parameter in the base class, because 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.
type MyState = {}
class App extends React.Component<{}, MyState> { state: MyState = {} }

For the section on Typing DefaultProps:

  • I strongly do not recommend annotating defaultProps into a Partial of your Props interface. This causes issues that are a bit complex to explain here 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. Don't do this! Instead this pattern is recommended:
type Props = Required<typeof MyComponent.defaultProps> & { /* additional props here */ }

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

For the section on Forms and Events:

  • I would just add that inlining the event handler when you don't need to optimize is recommended for better type inference:
// instead of this:
const myHandler = (event: React.MouseEvent<HTMLButtonElement>) => {}
const el = <button onClick={myHandler} />

// do this:
const el = <button onClick={event => {}} />

This tells the compiler that there is no ambiguity to when the handler is being used, and adding function types to the call site allows it to infer the event parameter's types right away.

That's all for now. I can definitely make a PR if y'all agree to these changes!

How to assign types to components?

I'm writing a component for React Native that shrinks or grows an image, depending on whether the keyboard is showing or not. I've already written and used in in JS. My recent project uses TypeScript. So I thought I could easly port it over. Well it turns out, I get the error message:

Property 'keyboardDidShowListener' does not exist on type 'Logo'.

Here is the code for the component:

import styles, { imageSizes } from "./styles";
import React, { Component } from "react";
import { Animated, Keyboard, Platform, View, EmitterSubscription } from "react-native";

const ANIMATION_DURATION = 250;

interface Props {}
interface State {
  containerImageWidth: Animated.Value;
}

export default class Logo extends Component<Props, State> {
  state = { containerImageWidth: new Animated.Value(imageSizes.$largeContainerSize) };

  componentDidMount = () => {
    const name = Platform.OS === "ios" ? "Will" : "Did";
    this.keyboardDidShowListener = Keyboard.addListener(
      `keyboard${name}Show`,
      this.keyboardWillShow
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      `keyboard${name}Hide`,
      this.keyboardWillHide
    );
  };

  componentWillUnmount = () => {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  };

  keyboardWillShow = () => {
    Animated.timing(this.state.containerImageWidth, {
      toValue: imageSizes.$smallContainerSize,
      duration: ANIMATION_DURATION
    }).start();
  };

  keyboardWillHide = () => {
    Animated.timing(this.state.containerImageWidth, {
      toValue: imageSizes.$largeContainerSize,
      duration: ANIMATION_DURATION
    }).start();
  };

  render() {
    const containerImageStyles = [
      styles.containerImage,
      { width: this.state.containerImageWidth, height: this.state.containerImageWidth }
    ];

    return (
      <View style={styles.container}>
        <Animated.View style={containerImageStyles}>
          <Animated.Image
            resizeMode="contain"
            style={containerImageStyles}
            source={require("../../assets/logos/logo.png")}
          />
        </Animated.View>
      </View>
    );
  }
}

The lines

...
this.keyboardDidShowListener = Keyboard.addListener
...
this.keyboardDidHideListener = Keyboard.addListener
...

Throw the aforementioned error.

I tried fixing it by declaring:

keyboardDidShowListener: EmitterSubscription;

below the state. But this throws the error:

Property 'keyboardDidShowListener' has no initializer and is not definitely assigned in the constructor.

How would you fix this?

[Improvement/Addition] Extracting and composing types using $ElementProps

Just thought i'd note something that i do, that may be useful for others.
Since TS 2.8's conditional types, its possible to extract a type parameter from another type (although maybe it was possible before but i didn't know how to do it).
This is essentially a port of flow's react utility type "ElementProps".
It allows you to extend another component easily, which assists with typing HOCs, and props spread.

eg:

// ReactUtilityTypes.d.ts
declare type $ElementProps<T> = T extends React.ComponentType<infer Props>
  ? Props extends object ? Props : never
  : never;

Then say you have some components which spread props to its child (almost like defaultProps, mapProps, withProps HOCs)
https://github.com/acdlite/recompose/blob/master/docs/API.md#withprops

//Components.tsx

/*
Std box component.
Eg <Box  display="flex" justifyContent="center" color="palevioletred" />
*/
const Box = (props: React.CSSProperties) => <div style={props} />

const Card =  ({title, children, ...props}: {title: string} & $ElementProps<typeof Box>) =>
<Box {...props}>{title}: {children}</Box>

We could have just used React.CSSProperties in place of $ElementProps<...>, but thats not really what we're trying to express. What if the component was from a 3rd party library and you didn't know where the Props interface was?
Eg:

import Paper from '@material-ui/core/Paper';

const Card =  ({title, children, ...props}: {title: string} & $ElementProps<typeof Paper>) =>
<Paper {...props}>{title}: {children}</Box>

Not only that, you can use https://github.com/piotrwitek/utility-types to express even more:

import Paper from '@material-ui/core/Paper';
import {Omit} from 'utility-types'

// Same as above except cannot be styled
const Card =  ({title, children, ...props}: {title: string} & Omit<$ElementProps<typeof Paper>, "style" | "className" | "classes">) =>
<Paper {...props}>{title}: {children}</Box>

Sorry if this is not succinct, just wasn't sure which parts are worth going in the cheatsheet or if other people would find this valuable.

Happy to write something more cheatsheet worthy or presentable if needed!

Extract proptypes in Typescript (interfaces)

How can I extract the proptypes (the interface) of a component in Typescript? I Know I can access the component and get the props easily, but I want to get the types, so that I can easily generate a nice show-case for my lib components.

Misleading assumption about IDE capabilities

The "enum" part of the advanced section mentions the following:

A simpler alternative to enum is just declaring a bunch of strings with union, but this doesn't get autocompletion or syntactic benefits:

This is quite possible with WebStorm. Given

type Foo = 'a' | 'b'
const foo: Foo = 

and hitting Ctrl + Space, you'll get a list of "a" and "b" which you can choose from. For longer strings, you'll also get suggestions as you start typing them (including the camelCase autocompletion, etc.)

The autocompletion capabilities should generally not be mentioned in the guide at all since it pretty much depends on what software you're using for development, or at least it should mention which IDE (like Webstorm) or text editor (like VSC) did the writer have in mind.

[Basic] Custom hooks recommendation idea

What cheatsheet is this about? (if applicable)

Basic cheatsheet

What's your issue or idea?

Our team uses custom hooks a lot. We are testing out the idea to return objects rather than arrays. You see, it makes sense for the generic hook functions to return arrays because it's almost always useful to grab both the state and the setState function. Also the react provided hooks don't really know what you're going to "call" or "name" the hook variables. However when you write a custom hook it's very useless to return an array because you're now requiring the caller to grab and name every variable that is returned (up until the last variable they plan on using). With an object return, you provide a bag of named variables (which makes much more sense for a custom hook). That way the caller of the hook can decide to grab JUST the variables they might be interested in, and are not forced to make unused variables if they just want the setter, for example.

How to handle conditional rendering?

Consider the following example:

type Component1Props = { ... }
const Component1: React.SFC<Component1Props> = props => { ... }

type Component2Props = { ... }
const Component2: React.SFC<Component2Props> = props => { ... }

const Component3: React.SFC<???> = props => {
   // some prop from Component1Props
   if(props.prop1) {
      return <Component1 {...props} />
   }
   
   // some prop from Component2Props
   if(props.prop2) {
      return <Component2 {...props} />
   }
}

Ideally I want typechecker to handle two things:

  1. It's required to pass either prop1 or prop2, but not both of them
  2. If prop1 is passed then props are of type Component1Props and if prop2 is passed then props are of type Component2Props

P. S. I'm completely new to TypeScript and I'm not sure that it's even possible)

[Basic] Function Component alternative

What cheatsheet is this about? (if applicable)

Basic cheatsheet

What's your issue or idea?

The function component can be reduced to

function App({ message: string }) {
  return <div>{message}</div>;
}

instead of

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

which is quite big & is weird syntactically at least in vanilla JS

const App = function App({ message ) {
  return <div>{message}</div>;
}

Also, would love some examples in Function Components section of What's the difference? each bullet points :)

Examples would be much better on these 2 bullet points since it makes grasping easier -

  • If you need to use children property inside the function body, in the former case it has to be added explicitly. FunctionComponent 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

Link to official CRA

There is an official release of create-react-app with TypeScript support that will be available very shortly.

How do you feel about updating the docs to reference create-react-app directly instead of the wmonk/jpavon forks when the new version lands?

Also for reference: facebook/create-react-app#5581

HOC typing example seems to be no longer valid as of [email protected]+

image

[email protected]
@types/[email protected]

The code from the Advanced section

Type '{ prop: string; } & Readonly<{ children?: ReactNode; }> & Readonly<Pick<T, Exclude<keyof T, "prop">>>' is not assignable to type 'IntrinsicAttributes & T & { children?: ReactNode; }'.
  Type '{ prop: string; } & Readonly<{ children?: ReactNode; }> & Readonly<Pick<T, Exclude<keyof T, "prop">>>' is not assignable to type 'T'.ts(2322)
import React from 'react'

type WithThemeProps = {
  prop: string;
}

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type Optionalize<T extends K, K> = Omit<T, keyof K>;

export function withTheme<T extends WithThemeProps = WithThemeProps>(WrappedComponent: React.ComponentType<T>) {
  // Try to create a nice displayName for React Dev Tools.
  const displayName = WrappedComponent.displayName || WrappedComponent.name || "Component";

  // Creating the inner component. The calculated Props type here is the where the magic happens.
  return class ComponentWithTheme extends React.Component<Optionalize<T, WithThemeProps>> {
    public static displayName = `withPages(${displayName})`;

    public render() {
      // this.props comes afterwards so the can override the default ones.
      return <WrappedComponent prop="prop" {...this.props} />;
    }
  }
}

Generic Components

What cheatsheet is this about? (if applicable)

Advanced cheatsheet

What's your issue or idea?

We should probably have a short section on authoring generic components -- components that take generic prop interfaces (or even state interfaces).

Omit attribute from a type convoluted

In the section Omit attribute from a type you suggest the following snippet:

// 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

This is only necessary in TypeScript versions prior to 2.8 since it includes Excludes which simplifies writing Omit as seen in previous parts of the cheat sheet:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

I'd like to change that - any objections against a PR?

[Suggestion] Extracting props of a component

Not sure where to put it, but I have these helper types in my team's codebase to extract the props of a component:

// helper type for all known valid JSX element constructors (class and function based)
type ElementConstructor<P> =
  | ((props: P) => React.ReactElement<any> | null)
  | (new (props: P) => React.Component<P, any, any>

// gets the internal props of a component
// used like Props<typeof MyComponent>
// or Props<'button'> for intrinsic HTML attributes
type Props<C> = C extends ElementConstructor<infer P>
  ? P
  : C extends keyof JSX.IntrinsicElements
  ? JSX.InstrinsicElements[C]
  : {}

// goes one step further and resolves with propTypes and defaultProps properties
type ApparentProps<C> = C extends ElementConstructor<infer P> ? JSX.LibraryManagedAttributes<C, P> : Props<C>

As far as how we use them, there's a lot of places where I want to reuse some slices of props because of prop drilling, and I can either export the props type as part of the module or I use this (either way works), the advantage of using this is that a refactor of the source of truth component will propagate to all consuming components.

I also use them to strongly type custom event handlers if they're not written at the call sites themselves (i.e. inlined with the JSX attribute):

// my-inner-component.tsx
export function MyInnerComponent(props: { onSomeEvent(event: ComplexEventObj, moreArgs: ComplexArgs): SomeWeirdReturnType }) { /* ... */ }

// my-consuming-component.tsx
export function MyConsumingComponent() {
  // event and moreArgs are contextually typed along with the return value
  const theHandler: Props<typeof MyInnerComponent>['onSomeEvent'] = (event, moreArgs) => {}
  return <MyInnerComponent onSomeEvent={theHandler} />
}

[translation] Add a translation link

Hi:
Thanks the great repo. I like it very much and I translated it into Chinese so more Chinese developer can read it easier, here's the repo link, would you like to add the link somewhere so more people may see this great repo? And I'll update the translation due to your updating. 😆
Best regards.

Thank you!

Just wanted to say what a phenomenal resource this is, even for experienced TypeScript developers. Thank you!

Generic Component with forwarded ref.

Hello everyone,

today I stumbled across the following problem:

I want to build a List Component that has a generic prop . From the outside you can pass a ref to the List, to access a scrollToItem(item: TItem). Since I want to use hooks, I need to use React.forwardRef, which does not allow to return a generic function.

This is my attempt of solving, but I feel like there could be something less verbose and repetitive.

type ListRef<ItemType> = {
  scrollToItem: (item: ItemType) => void;
};

type ListProps<ItemType> = {
  items: ItemType[];
};

const List = forwardRef(function List<ItemType>(props: ListProps<ItemType>) {
  useImperativeHandle<ListRef<ItemType>, ListRef<ItemType>>(ref, () => ({
    scrollToItem: (item: ItemType) => undefined
  }));

  return null;
}) as <ItemType>(
  p: ListProps<ItemType> & { ref: Ref<ListRef<ItemType>> }
) => ReactElement<any> | null;

let ref = useRef<ListRef<number>>(null);

<List items={[1, 2, 3]} ref={ref} />;

Types vs Interfaces

Spectrum discussion here brought up the Types vs Interfaces discussion. as far as I can tell there is no real difference between them. I personally always use interfaces but i dont have a strong reason apart from I can extend them if i need to. Should we recommend one or the other? anyone have a source?

Assigning a type to a string that you are using as a react constructor

Hard to figure out how to write this, so I'll just give an example:

Example:

type Props = {
  headerTag: 'h1' | 'h2' | 'h3';
}

const ParentComponent: React.FC<Props> = (props) => {
  const HeaderTag = props.headerTag;
  const text = "Please someone help me type this correctly.";

  return <HeaderTag>{text}</HeaderTag>;
}

Error:

Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes'.

It doesn't like me giving any children to <HeaderTag> even though I know <h1> etc. can obviously have string children.

I tried typing the HeaderTag variable but I didn't know what to type it as, because Typescript knows headerTag is just a string.

The solution I came up with isn't really what I want to do, since it uses React.createElement:

return React.createElement(props.headerTag, {}, text)

How should I be doing?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.