I am working with an enum that represents different types of nodes in a tree structure.
enum MyEnum {
'A' = 'A',
'B' = 'B',
'C' = 'C',
// ...
}
Each node in the tree has specific types of children nodes that are allowed.
type ChildrenAllowed<T extends MyEnum> = T extends MyEnum.A
? MyEnum.B | MyEnum.C
: T extends MyEnum.B
? MyEnum.C
: undefined;
I am trying to create a function that will return an array of allowed node types, but I am encountering type errors. Can you help me figure out what I am missing?
const getChildrenAllowedTypes = <T extends MyEnum>(
p: T,
): ChildrenAllowed<T>[] => {
switch (p) {
case MyEnum.A:
return [
MyEnum.B, // Error: Type 'E.B' is not assignable to type 'O'.
MyEnum.C, // Error: Type 'E.C' is not assignable to type 'O'.
];
case MyEnum.B:
return [
MyEnum.C, // Error: Type 'E.C' is not assignable to type 'O'.
];
default:
return [];
}
};
Here is a simplified object structure that is not directly related to the problem at hand.
// simplified object structure
type ChildrenOwner<TCurrent extends MyEnum> = {
children?: Children<TCurrent>;
};
type Children<
TCurrent extends MyEnum,
TChildrenAllowed = ChildrenAllowed<TCurrent>,
> = {
[TKey in TChildrenAllowed & string]?: TKey extends MyEnum
? ChildrenOwner<TKey>
: undefined;
};