Reactjs – TypeScript types for React component where prop is an array of objects

reactjstypescript

My React component has a prop called propWhichIsArray which will be an array of objects. These objects will have an id which is an ID and text which is a string. How can you type this with TypeScript?

type Props = {
  propWhichIsArray: {
    id,
    text: string;  
  }[]
};

const Component: React.FC<[Props]> = ({ propWhichIsArray }) => {
  //

Im getting an error:

Property 'propWhichIsArray' does not exist on type '[Props] & { children?:
ReactNode; }'. TS2339

Best Answer

The main issue is that you're doing React.FC<[Props]> instead of React.FC<Props>. With the square brackets, you're creating a tuple type, whose's zeroth element is of type Props, and then you're having that tuple be the props of your component. Additionally, i'd probably specify the props as an interface.

interface Props {
  propWhichIsArray: {
    id: ID; // I assume ID is defined elsewhere
    text: string;
  }[]
}

const Component: React.FC<Props> = ({ propWhichIsArray }) => {

If this data in the array is being used in other places, you may want to pull it out to its own interface:

interface Thingamajig {
  id: ID;
  text: string;
}

interface Props {
  propWhichIsArray: Thingamajig[];
}