4.4 - Type Safe React
TypeScript is a popular way to add type definitions to JavaScript codebases! Writing TypeScript with React is very similar to writing JavaScript with React.
The key difference when working with a component is that you can provide types for your component’s props. These types can be used for correctness checking and providing inline documentation in editors.
Every file containing JSX must use the .tsx
file extension. This is a TypeScript-specific extension that tells TypeScript that this file contains JSX.
For example, we can add a type describing the title in the MyButton component.
function MyButton({ title }: { title: string }) {
return (
<button>{title}</button>
);
}
This inline syntax is the simplest way to provide types for a component, though once you start to have a few fields to describe it can become unwieldy. Instead, you can use an interface or type to describe the component’s props:
interface MyButtonProps {
/** The text to display inside the button */
title: string;
/** Whether the button can be interacted with */
disabled: boolean;
}
function MyButton({ title, disabled }: MyButtonProps) {
return (
<button disabled={disabled}>{title}</button>
);
}
The type describing your component’s props can be as simple or as complex as you need, though they should be an object type described with either a type
or interface
.