Typescript: Typing number of children in TSX

Created on 21 Mar 2018  路  3Comments  路  Source: microsoft/TypeScript

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

Committed Suggestion

Most helpful comment

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

All 3 comments

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

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

@weswigham amazing, thanks!

Was this page helpful?
0 / 5 - 0 ratings