How to a create class component using TypeScript

Create a new file with a component name, for example, Counter.tsx.

Inside, create a class component as you would in plain React:

Then, create a CounterProps type to define props that the component will accept and a CounterState type to type the state of a component if it has one.

The CounterProps type is used to declare what type the properties of this component support.

This is similar to declaring types with prop-types but without any additional packages and the result of type checking is available at design time. You won't need to run the project to figure out that some types are not correctly passed.

The same with the CounterState type—it will check the state types at the pre-compile time, so you will know earlier if there is an error.

You don't have to annotate CounterState the second time inside of a component itself, but it allows better type inference when accessing this.state.

Notice the React.Component<CounterProps, CounterState>T type. This is the generic React.Component type. It takes two type-parameters that tell TypeScript how to interpret types of component props and state, so TypeScript can derive types of each field in props and the state.

There is no need to mark types fields readonly since React.Component<P,S> already marks them as immutable.

Components Without State#

If your component doesn't need any state you can declare it without a state at all:

Class Methods#

Class Methods on a component are useful when you have to perform some action and want to extract its logic in a function. (In the example below, we log into a console the counter values.)

You can define class methods as usual except for typing all of the arguments and return values:

Class Properties#

Class properties are useful for storing some data that should not affect re-render of a component.

In the example below, it is a helloMessage that changes when a component is mounted. Its update won't trigger re-rendering.

You can define class properties like plain TypeScript class properties with their type declarations: