Defining Props and State Types
In this tutorial, you will learn how to define props and state types in TypeScript for both functional and class components. Doing so ensures type safety and maintainable code in your React applications.
Functional Components
Props
When using TypeScript with functional components, you can define the expected prop types using type annotations:
import React from 'react';
type Props = {
message: string,
};
const Greeting: React.FC<Props> = ({ message }) => {
return <h1>{message}</h1>;
};
export default Greeting;
In this example, we define a Props
type for the component's props. The Greeting
component is then typed as React.FC<Props>
to specify the expected prop types.
State
To use state in a functional component, you can use the useState
hook and provide a type for the state value:
import React, { useState } from 'react';
type Props = {
message: string,
};
const Counter: React.FC<Props> = ({ message }) => {
const [counter, setCounter] = useState < number > 0;
const increment = () => {
setCounter(counter + 1);
};
return (
<div>
<h1>{message}</h1>
<p>Counter: {counter}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
export default Counter;
In this example, we provide the <number>
type for the counter
state value.
Class Components
Props
For class components, you can define prop types by extending the Component
class with the expected prop types:
import React, { Component } from 'react';
type Props = {
message: string,
};
class Greeting extends Component<Props> {
render() {
const { message } = this.props;
return <h1>{message}</h1>;
}
}
export default Greeting;
In this example, the Greeting
component extends Component<Props>
to specify the expected prop types.
State
For class components, you can define state types by extending the Component
class with the expected prop and state types:
import React, { Component } from 'react';
type Props = {
message: string,
};
type State = {
counter: number,
};
class Counter extends Component<Props, State> {
state: State = {
counter: 0,
};
increment = () => {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
};
render() {
const { message } = this.props;
const { counter } = this.state;
return (
<div>
<h1>{message}</h1>
<p>Counter: {counter}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
In this example, the Counter
component extends Component<Props, State>
to specify the expected prop and state types.
Conclusion
Now you know how to define props and state types in TypeScript for both functional and class components in React. This practice will help you ensure type safety and maintainable code in your projects.