After recently learning TypeScript, I encountered an error that made me think I need to write a narrower type for it or something along those lines.
Here is the code snippet in question:
enum ElementTypes {
h1 = 'H1',
word = "WORD"
}
type DefaultElementType<T> = {
children: string[];
id: number | string;
type: T;
};
type H1Element = DefaultElementType<ElementTypes.h1>;
type WordElement = DefaultElementType<ElementTypes.word> & {
value: string;
}
type CustomElement =
| H1Element
| WordElement
const insertNode = (element: CustomElement) => {
// do sth here, not important
}
const addInsertNode = ({type, id}: {type: ElementTypes, id: number | string}) => {
insertNode({type, id, children:[], ...(type === ElementTypes.word ? {value: 'some value'}: {})})
}
And here is the error message it generated:
Argument of type '{ value?: string | undefined; type: ElementTypes; id: string | number; children: never[]; }' is not assignable to parameter of type 'CustomElement'.
Type '{ value?: string | undefined; type: ElementTypes; id: string | number; children: never[]; }' is not assignable to type 'WordElement'.
Type '{ value?: string | undefined; type: ElementTypes; id: string | number; children: never[]; }' is not assignable to type 'DefaultElementType<ElementTypes.word>'.
Types of property 'type' are incompatible.
Type 'ElementTypes' is not assignable to type 'ElementTypes.word'.
I attempted to use Discriminated Unions to address this issue, but unfortunately, it did not resolve it.
Here is a playground showcasing the error.
Any help on this matter would be greatly appreciated.