TypeScript ยท Chapter 43 of 44

TypeScript with React

TypeScript pairs very well with React, letting you type component props, state, and event handlers so mistakes are caught before your app even runs. React components are typically written in .tsx files.

You can type a functional component's props using an interface or type alias, and TypeScript will warn you if you forget a required prop or pass one of the wrong type when using that component.

Syntax
interface ButtonProps {
  label: string;
  onClick: () => void;
}
function Button({ label, onClick }: ButtonProps) { /* ... */ }

Typing props

You define a props interface, like `interface ButtonProps { label: string; onClick: () => void; }`, and use it as the type for the component's parameter, giving full autocomplete and checking.

Typing state and events

React's `useState<T>()` hook can be given an explicit type argument, and event handler parameters can be typed with React's built-in event types like `React.MouseEvent`.

Example 1 (typescript)
interface ButtonProps {
  label: string;
  onClick: () => void;
}
function Button({ label, onClick }: ButtonProps) {
  return `<button>${label}</button>`; // simplified for illustration
}
console.log(Button({ label: "Save", onClick: () => console.log("Saved") }));
Output
<button>Save</button>

The ButtonProps interface ensures label and onClick are always provided with the correct types.

Example 2 (typescript)
function useCounterExample() {
  let count: number = 0;
  function increment(): number {
    count += 1;
    return count;
  }
  return increment;
}
const increment = useCounterExample();
console.log(increment());
console.log(increment());
Output
1
2

This simplified example mirrors how useState<number>() keeps count strongly typed as a number in real React code.

Key points

  • React components in TypeScript are usually written in .tsx files.
  • Props are typically typed with an interface or type alias.
  • useState<T>() can be given an explicit type for its state value.
  • TypeScript catches missing or mistyped props before the app runs.
๐Ÿ’ก Note: Most popular React libraries ship their own TypeScript types, making integration smooth.

๐Ÿ“ Quick Quiz

1. What file extension do React components typically use with TypeScript?

2. How do you typically type a component's props?

3. How can you give useState an explicit type?