Reputation: 4260
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
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
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];
Upvotes: 0