I’ve some typescript definitions like this:
interface T1 {
children: string[];
}
interface T2 {
children?: number | boolean | undefined | null;
}
type All = T1 & T2;
const b: All = {
children: ['test'],
};
I’m wondering what type exactly is the All[‘children’] property?
I can’t assign string array to it and don’t know how I can use this intersection type .
In real life, React.js has a children definition on React.Component, when I define my own children type, there is no error in this case.
UPDATE, add some real life code in React Native code. I have the following definition:
interface Props {
children: View[];
}
export default Demo extends React.Component<Props> {
}
// later in parent component
<Demo>
<View></View>
<View></View>
</Demo>
I can't find out why typescript can handle the children for Demo. this is the children definition in React.Component
{
children?: ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
}
so, In my opinion, the final type of children in Demo should be:
children: (View[] & ReactChild) | (View[] & ReactFragment) | (View[] & ReactPortal) | (View[] & boolean) | (View[] & null) | (View[] & undefined)
How can I pass View arrays to Demo as children.
UPDATE AGAIN, I find that, ReactFragment definition is the key point.
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
{} in ReactFragment, results in View[] & {}, which is equivalent to View[]
All['children']equivalent tonever, but component children have a lot more allowed types than your example here.Reactchildrenhave a lot more types, but I don’t find out why. if I definechildren: View[]in myPropsand with React’schildrendefiniionchildren?: ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;, according to my understanding, the final types should beView[] & ReactChild | View[] & ReactFragment | View[] & ReactPortal | View[] & boolean | View[] & null | View[] & undefined;. When I useView Arrayaschildrenin my component, there’s no errror. I don’t see the difference betweenReactchildren and my demo definitionReact.Componentchildren definition,type ReactFragment = {} | ReactNodeArray;which solve this problem