How to Type Props in TypeScript
When working with TypeScript, one of the key aspects is properly typing the props passed to components. This ensures type safety and helps catch potential errors early on. In this article, we will explore different ways to type props in TypeScript.
1. Inline Type Annotation
One way to type props is by using inline type annotation. This involves explicitly defining the type of each prop directly in the component’s declaration.
interface MyComponentProps {
name: string;
age: number;
}
const MyComponent: React.FC = ({ name, age }) => {
return (
Name: {name}
Age: {age}
);
};
In this example, we define an interface MyComponentProps
which specifies the expected props for MyComponent
. The component is then annotated with React.FC
to indicate that it accepts these props.
2. PropTypes
If you are using a library like PropTypes, you can leverage it to type your props in TypeScript. PropTypes provides a way to define the expected types for props, and TypeScript can infer those types.
import PropTypes from 'prop-types';
const MyComponent = ({ name, age }) => {
return (
Name: {name}
Age: {age}
);
};
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};
In this example, we import PropTypes and use it to define the expected types for name
and age
. TypeScript will infer the types based on the PropTypes declarations.
3. Default Props
Another way to type props is by providing default values. This can be useful when some props are optional or have a default value.
interface MyComponentProps {
name: string;
age?: number;
}
const MyComponent: React.FC = ({ name, age = 18 }) => {
return (
Name: {name}
Age: {age}
);
};
In this example, we define the age
prop as optional by using the ?
symbol. We also provide a default value of 18 for the age
prop in case it is not provided.
Conclusion
Properly typing props in TypeScript is crucial for maintaining type safety and catching potential errors. In this article, we explored three different ways to type props: inline type annotation, PropTypes, and default props. Choose the approach that best suits your project and enjoy the benefits of TypeScript’s static typing.
That’s it for this article. Happy typing!
Leave a Reply