Creating strongly-typed class state

In this lesson, we are going to learn how to create a strongly-typed state in a class component.

Component without state type specified

We are going to use an exercise in CodeSandbox to work on a Counter component. The task will be similar to what we did for the function-based Counter component earlier in this course.

Click the link below to open the exercise in CodeSandbox:

CodeSandbox project

We are going to add the current count as a state to the Counter component. We’ll start by initializing the count state:

class Counter extends React.Component {
  state = {
    count: 0
  }
  render() {
    return <button>Click to start counter</button>;
  }
}

Alternatively, we could initialize the count state in a constructor as follows:

class Counter extends React.Component {
  constructor(props: {}) {
    super(props);
    this.state = {
      count: 0
    };
  }
  render() {
    return <button>Click to start counter</button>;
  }
}

It’s up to you which state initialization approach you use - the TypeScript typing works well with both approaches.

Let’s also increment the count when the button is clicked and output the count in the button:

render() {
  return (
    <button onClick={() => this.setState((state) => ({count: state.count + 1}))}>
      {this.state.count ? this.state.count : "Click to start counter"}
    </button>
  );
}

The component does function as we want, but we have type errors where the count state is referenced:

Get hands-on with 1200+ tech skills courses.