traintocode

Adding Types to Props

TypeScript enables strong typing for component props using interfaces or types, allowing you to define the shape and types of the props your component expects. When you apply these types to your React components, TypeScript provides compile-time errors for any mismatches or missing properties.

For example, if your component expects a title (string) and a count (number), define a type like this:

type Props = {
  title: string;
  count: number;
}

Then pass this type into the generic type parameter of the React.FC<> component function:

const YourComponent: React.FC<Props> = ({ title, count }) => {
  // Component logic here
};

With this structure, you can use TSX as usual and TypeScript will ensure that the props passed to the component match the expected types.

Exercise
Modify this React component to accept a name prop of type string, and display the name inside the header

Ask for help or clarification if you need to:

    You cannot do the coding exercises on this device, visit this page on a larger screen.
    App.tsx
    Loading...