14

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

1 Answer 1

30

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.

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[];
}
Sign up to request clarification or add additional context in comments.

1 Comment

That second interface with the strongly typed array as a property in Props is what I always forget to do. Trying to burn that into my brain!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.