Skip to content

Typing number of children in TSX #22759

Closed

Description

@methyl

Imagine a component which requires some exact number of children passed.

Can it be currently expressed in TypeScript? Tuple doesn't work here.

Code

import React from 'react'

interface ResizablePanelProps {
  children: [React.ReactNode, React.ReactNode]
}

class ResizablePanel extends React.Component<
  ResizablePanelProps, any> {}

const test = <ResizablePanel>
  <div />
  <div />
</ResizablePanel>

Expected behavior:
Pass.

Actual behavior:

Type '{ children: Element[]; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<ResizablePanel> & Readonly<{ children?: ReactNode;...'.
  Type '{ children: Element[]; }' is not assignable to type 'Readonly<ResizablePanelProps>'.
    Types of property 'children' are incompatible.
      Type 'Element[]' is not assignable to type '[ReactNode, ReactNode]'.
        Property '0' is missing in type 'Element[]'.

Code

import React from 'react'

interface ResizablePanelProps {
  children: [React.ReactNode, React.ReactNode]
}

class ResizablePanel extends React.Component<
  ResizablePanelProps, any> {}

const test = <ResizablePanel>
  <div />
  <div />
  <div />
</ResizablePanel>

Expected behavior:
Fail, provided 3 nodes instead of 2.

Playground Link:
https://stackblitz.com/edit/react-ts-8tttua

Activity

  1. RyanCavanaugh commented on Mar 21, 2018

    @RyanCavanaugh
    Member

    Wesley Wigham (@weswigham) I think we can just force tuple inference for the JSX children array and this should work automagically. Thoughts?

  2. weswigham commented on Mar 21, 2018

    @weswigham
    Member

    At least it should be doable to make the tupleness propegate via contextual type like it does elsewhere.

  3. methyl commented on Oct 5, 2018

    @methyl
    Author
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

CommittedThe team has roadmapped this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions