TypeScript and React - children type?

前端 未结 14 1260
借酒劲吻你
借酒劲吻你 2020-12-12 18:56

I have a very simple functional component as follows:

import * as React from \'react\';

export interface AuxProps  { 
    children: React.ReactNode
 }


con         


        
14条回答
  •  無奈伤痛
    2020-12-12 19:04

    The function component return type is limited to JSXElement | null in TypeScript. This is a current type limitation, pure React allows more return types.

    Minimal demonstration snippet

    You can either use a type assertion or Fragments as workaround:

    const Aux = (props: AuxProps) => <>props.children; 
    const Aux2 = (props: AuxProps) => props.children as ReactElement; 
    

    ReactNode

    children: React.ReactNode might be suboptimal, if the goal is to have strong types for Aux.

    Almost anything can be assigned to current ReactNode type, which is equivalent to {} | undefined | null. A safer type for your case could be:

    interface AuxProps {
      children: ReactElement | ReactElement[]
    }
    

    Example:

    Given Aux needs React elements as children, we accidently added a string to it. Then above solution would error in contrast to ReactNode - take a look at the linked playgrounds.

    Typed children are also useful for non-JSX props, like a Render Prop callback.

提交回复
热议问题