Creating strongly-typed class props
Explore how to create and use strongly-typed props in React class components with TypeScript. Understand specifying props inline, using type aliases and interfaces, handling optional and default props, destructuring, and incorporating object and function props. This lesson helps you write type-safe and readable components by leveraging TypeScript's features.
We'll cover the following...
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:
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>;
}
}
...