Ramon Balthazar
Ramon Balthazar

Reputation: 4260

In React, how to restrict the number of children with Typescript?

I'm creating a "Columns" component. It should only take either one or two children.

How do I restrict the number of children using Typescript?

Upvotes: 2

Views: 909

Answers (2)

Jap Mul
Jap Mul

Reputation: 18769

This seems to work

import * as React from "react";

type ChildType = React.ReactElement;

interface ColumnProps {
  children: [ChildType, ChildType] | ChildType; // Either 2 of this type or one
}

const Column: React.FC<ColumnProps> = ({ children }) => {
  return <div>{children}</div>;
};

export default function App() {
  return (
    <div className="App">
      <Column>
        <div>Test 1</div>
        <div>Test 2</div>
      </Column>
    </div>
  );
}

Upvotes: 3

Mike F
Mike F

Reputation: 368

Looking at this answer I think this might work?

type Column = {
    foo: string;
}

type ArrayOneOrMore<T> = {
    0: T
} & Array<T>

type Columns = ArrayOneOrMore<Column>;

const ColumnOne = {
    foo: 'bar'
}

const ColumnTwo = {
    foo: 'bar'
}

const WithOneColumn: Columns = [ColumnOne, ColumnTwo];
const WithTwoColumns: Columns = [ColumnOne];

TypeScript Playground

Upvotes: 0

Related Questions