Currently, I am in the process of transitioning from PropTypes to TypeScript within a large React Native project. Within the codebase, there are multiple components utilizing child classes for improved name scoping and organization. To illustrate this concept, consider the following simplified example:
const styles = StyleSheet.create({
listItem: ...,
leftItem: ...,
contentItem: ...,
rightItem: ...,
})
const ListItemLeft = ({ children }) => <View style={styles.leftItem}>{children}</View>;
const ListItemContent = ({ children }) => <View style={styles.contentItem}>{children}</View>;
const ListItemRight = ({ children }) => <View style={styles.rightItem}>{children}</View>;
class ListItem extends Component {
render() {
let left = null, right = null, content = null;
const otherChildren = [];
React.Children.forEach(children, child => {
if (child) {
if (child.type.name === Left.name) {
left = child;
} else if (child.type.name === Right.name) {
right = child;
} else if (child.type.name === Content.name) {
content = child;
} else {
otherChildren.push(child);
}
}
});
return (
<div style={styles.listItem}>
{left}
{content}
{right}
{otherChildren}
</div>
);
}
}
ListItem.Left = ListItemLeft;
ListItem.Content = ListItemContent;
ListItem.Right = ListItemRight;
export default ListItem;
To utilize this on a page, you would do something like this:
<ListItem>
<ListItem.Left>Left content</ListItem.Left>
<ListItem.Content>Main content</ListItem.Cotent>
<ListItem.Right>Right content</ListItem.Right>
<ListItem>
While converting this to TypeScript, the challenge lies in determining how to test the children's types and assign them to the variables accordingly.
let left : ListItemLeft | null = null,
right : ListItemRight | null = null,
content : ListItemContent | null = null;
React.Children.forEach<ReactNode>(children, child => {
/* How can we accurately test the type of child and assign it to left, right, content or other? /*
});