vhflat
vhflat

Reputation: 589

How can I specify length of children when type checking props?

I want my component to only accept 3 children of type React.ReactChild. Tho I'm not sure if ReactChild is the best type to check for. It's basically three sections.

function TopBox({ children }: Props) {
  return (
    <Container>
      {children}
    </Container>
  );
}

Right now I've got something that works. But I'm looking for a shorter expression for this.

interface Props {
  children: [
    React.ReactChild,
    React.ReactChild,
    React.ReactChild
  ]
}

Upvotes: 0

Views: 456

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249796

The important property is length in a tuple. We can use an intersection between an array and a { length: 3 } type to simulate a tuple of a specific length. This is not exactly a tuple but it will do the job as far as length is concerned.

type ReactChildrenOfLength<T extends number> = [] | (React.ReactChild[] & { length: T })
interface Props {
    children: ReactChildrenOfLength<3>
}

function TopBox({ children }: Props) {
    return (
    <div>
        {children}
    </div>
    );
}

let d = <TopBox>
    <div></div>
    <div></div>
    <div></div>
</TopBox>

One piece of the code above that might cause a bit of confusion is the [] |. If children is not a tuple then Typescript will not bother with tuples for children and our length will have no impact. The [] | forces the compiler to use tuples when building the jsx children.

Upvotes: 2

Related Questions