Skip to content

Typing number of children in TSX #22759

Closed
@methyl

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

Metadata

Metadata

Assignees

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