Creating strongly-typed class props

Earlier in this course we learned how to create strongly-typed props for function components. In this lesson, we'll learn how to do this for class components.

Specifying props #

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

Click the link below to open the exercise in CodeSandbox:

CodeSandbox exercise

Class components inherit from the Component class in React. Component is a generic class that takes the props type in as a generic parameter:

class MyComponent extends React.Component<Props> { ... }

Let’s add a who prop to the Hello component by specifying the props type inline. Let’s also output the value of who after the Hello message.

class Hello extends React.Component<{ who: string }> {
  render() {
    return <p>Hello, {this.props.who}</p>;
  }
}

A red squiggly line should appear under the Hello component reference in the call to the render function. What is the problem that is being highlighted to us?

Get hands-on with 1200+ tech skills courses.