user1283776
user1283776

Reputation: 21834

Allow props.children to be anything when using Typescript with "no-any": true?

I want to be able to pass anything into my component as props.children. My first thought would be to set the type of props.children to any.

interface MyProps {
    children: any;
}

But unfortunately we specify "no-any": true in out tsconfig file.

So the solution that I have found working is:

interface TableProps {
    children: JSX.Element[] | JSX.Element | string;
}

But this feels very ugly. I dislike having to pass 3 arguments to mimic any. Is there a better way?

Upvotes: 1

Views: 52

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075895

If you're going to disallow any, you're pretty much going to have to be specific. But that doesn't mean repeating yourself. :-) You can define that union as a type:

type ComponentChildren = JSX.Element[] | JSX.Element | string;

...then use that type wherever you need to allow all three of those as children:

interface TableProps {
    children: ComponentChildren;
}

Upvotes: 2

Related Questions