Ayo Akindele
Ayo Akindele

Reputation: 43

TypeScript "TS2339: Property 'X' does not exist on type 'Y'" error even though type is defined

In my code, I'm trying to access the type property of a React.ReactElement array element. Even though I've defined the array to contain React.ReactElement children, I get an error trying to access an array element's type property unless I cast the array element to be of the type React.ReactElement.

Here's my code:

const getChildren = (
    children: (React.ReactChild | React.ReactElement)[]
) => {
    console.log((children[0] as React.ReactElement).type)  // this line works
    console.log(children[0].type)  // this line breaks
}

and here's the error that I get:

Property 'type' does not exist on type 'ReactChild | ReactElement<any, string | JSXElementConstructor<any>>'.
  Property 'type' does not exist on type 'string'.  TS2339

How can I resolve this issue?

Upvotes: 4

Views: 1409

Answers (1)

metodribic
metodribic

Reputation: 1729

I'm not familiar with React but I'm assuming that React.ReactChild has no attribute named type and this is the reason you are getting the error.

Typescript compiler has no idea of knowing which of the types (React.ReactChild or React.ReactElement) your item is unless you explicitly tell the compiler which one is it. This is why your first line in the function works, because you explicitly tell the compiler that the argument passed in the function is React.ReactElement[] or at least the first element in the array is the argument of type React.ReactElement.

If you know that elements in an array will always be a type of React.ReactElement then I suggest you to change the function argument type to be

const getChildren = (children: React.ReactElement[]) => {/* ... */}

otherwise you should check it which of the types is it to avoid runtime errors:

const getChildren = (children: (React.ReactChild | React.ReactElement)[]) => {
  if (children[0] instanceof React.ReactChild) {
    console.log(children[0].type);
  }
}

Upvotes: 3

Related Questions