I have a function that generates an array of objects called nodes:
type Node = {
type: 'text' | 'entity';
// A node of type 'entity' for sure has props defined while a 'text' node does not have them.
// I also require those nodes to be in the same array when returned from the buildNodes function
props?: EntitySpecificProps;
}
type EntitySpecificProps = {
id: string;
}
function buildNodes(): Node[] {
...
return nodes;
}
Now let's say I generate some nodes and pass them to another function which is defined as:
function useEntityNode(props: EntitySpecificProps){
...
}
const nodes = buildNodes();
// typescript gives error because node props may be possibly undefined (given the optional type of 'props').
nodes.map((node) => node.type === 'text' ? node : useEntityNode(node.props))
How can I constrain node props to be defined if the type field of a node is of type entity?