In my attempt to create a type that can be A, B, or an object with a key containing an array of 2 or more items that are either A, B, or another similar object (thus allowing for recursive definition).
This is the solution I came up with:
type A = {
prop1: string;
}
type B = {
prop2: number;
}
type Array = {
list: [AorB, AorB, ...AorB[]]
}
type AorB = A | B | Array;
type AorBorArray = AorB;
When used with just A or B values, it works perfectly:
const obj1 = { prop1: 'test' };
const a: A = obj1; // OK
const obj2 = { prop2: 123 };
const b: B = obj2; // OK
However, when attempting to assign a list to a variable of type AorBorArray
, it fails:
const list = {
list: [
{prop1: 'test'},
{prop2: 123}
]
};
const assignTest: AorBorArray = list; // Error
https://i.sstatic.net/nDkY2.png
The assignment only works if I explicitly cast the list
variable to AorBorArray
:
const list = {
list: [
{prop1: 'test'},
{prop2: 123}
]
} as AorBorArray;
const assignTest: AorBorArray = list; // OK
If I change the type definition of Array
to:
type Array = {
list: AorB[]
}
it also works. But I prefer to enforce having 2 or more items in the array.
Why is this happening? Since users will provide this object, I want to avoid them having to cast every time. How can I adjust the typings so that the assignment works seamlessly?
Thank you!