children.toArray() - TS2339: Property 'key' does not exist on type 'ReactChild | ReactFragment | ReactPortal'... - React Typescript

Viewed 408

I'm creating a TypeScript component/wrapper that adds a divider between each child:

import React, { FC, Children } from 'react'

const DividedChildren: FC = ({ children }) => {
  return (
    <div>
      {Children.toArray(children).map((node, index) => {
        if (index === 0) return node
        return (
          <Fragment key={node.key}> // TS Error, but code works fine
            <div className="divider" />
            {node}
          </Fragment>
        )
      })}
    </div>
  )

However, I'm getting a TypeScript error when I try to move the child's key into his new container:
TS2339: Property 'key' does not exist on type 'ReactChild | ReactFragment | ReactPortal'.   Property 'key' does not exist on type 'string'.

How can I type-safely move each item's key to its new container?

1 Answers

I've managed to get around this specific error by casting node as a ReactElement type.

Children.toArray(children).map((node: React.ReactElement, index) => { //...
Related