Why does type guard work for the object itself, but not for the clones of that object? Here is my code (playground link):
if (
node.data.children.type === NodeDataChildType.CHOICES &&
node.id === nodeId
) {
const newNode = { ...node };
console.log(
newNode.data.children.choices, // cloned object, giving error
node.data.children.choices // original object, no errors
);
}
(Please note: I know both choices
above are the same array since object spread just does a shallow clone. I'm logging both of them to demonstrate the type error on the cloned object.)
I'm getting this error:
Property 'choices' does not exist on type 'NodeDataChildren'.
Property 'choices' does not exist on type '{ type: NodeDataChildType.TEXT | NodeDataChildType.CONTINUE | NodeDataChildType.NONE; }'.ts(2339)
Here are the types:
export type Node = {
data: NodeData
id: string;
}
export type NodeData = {
label?: string;
children: NodeDataChildren;
};
type NodeDataChildren =
| {
type: Exclude<NodeDataChildType, NodeDataChildType.CHOICES>;
}
| {
type: NodeDataChildType.CHOICES;
choices?: Array<NodeDataChildChoice>;
};
export enum NodeDataChildType {
CHOICES = "choices",
TEXT = "text",
CONTINUE = "continue",
NONE = "none",
}
export type NodeDataChildChoice = {
id: string;
};
Note: This is not built in Node type, but a custom Node Type
What am I doing wrong here?