i recently have learnt typescript, i encountered an error that i think i should write type narrower for it or something like that.
here’s the code i wrote:
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 element = {
type: ElementTypes.h1,
id: 1,
children: []
}
const anotherElement: CustomElement = element;
and here’s the error it gives:
Type '{ type: ElementTypes; id: number; children: never[]; }' is not assignable to type 'CustomElement'.
Type '{ type: ElementTypes; id: number; children: never[]; }' is not assignable to type 'WordElement'.
Type '{ type: ElementTypes; id: 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’ve tried writing Discriminated Unions but it didn’t help.
here’s a playground of the error.
I would appreciate any help.
New contributor
Aryan Mehrabi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.