skip to Main Content

With this component:

<Component>example string</Component>

How to work around type children: "example string" resulting in the following Typescript error?

This JSX tag’s ‘children’ prop expects type ‘"example string"’ which requires multiple children, but only a single child was provided.ts(2745)


More context

It’s an icon component that receives the icon name as child ; the name can be any string between "stringA", "stringB", etc.

// in the file using the component
<Icon>stringA</Icon>

// in the component file
type IconProps = {
  children: (typeof iconNames)[number]
}

// in another file
export const iconNames = ["stringA","stringB",...,"stringZ"] as const

2

Answers


  1. Change the type to children: string without quotation marks to allow any single string, or, if you want the child to be a constant of "string", pass it as a constant:

    <Component>{'string' as const}</Component>
    
    Login or Signup to reply.
  2. You can attempt to define the type of the children prop in your TypeScript component

    type ComponentProps = {
      children: ReactNode
    }
    
    ....
    
    const App = () => {
       return (
         <Component>
           {"example string"}
         </Component>
       )}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search