I have an interface called Bounds, and a Sprite class with a field bounds of type Bounds[][]. The Sprite's constructor has a union type argument of Bounds[]|Bounds[][]. If the argument is type Bounds[], I want to simply wrap it in an array:
class Sprite {
constructor(bounds: Bounds[]|Bounds[][]) {
if (!bounds) {
this.bounds = [[ /* some default value */ ]];
} else {
if (!bounds.length) {
throw new Error('Argument \'bounds\' must not be empty.');
}
if (!Array.isArray(bounds[0])) {
this.bounds = [bounds];
} else {
this.bounds = bounds;
}
}
}
bounds: Bounds[][];
}
This code works, but the TypeScript compiler is giving me these errors for the second and third assignments, respectively:
Type '(Bounds[] | Bounds[][])[]' is not assignable to type 'Bounds[][]'.
Type 'Bounds[] | Bounds[][]' is not assignable to type 'Bounds[]'.
Type 'Bounds[][]' is not assignable to type 'Bounds[]'.
Type 'Bounds[]' is not assignable to type 'Bounds'.
Property 'x' is missing in type 'Bounds[]'.
Type 'Bounds[] | Bounds[][]' is not assignable to type 'Bounds[][]'.
Type 'Bounds[]' is not assignable to type 'Bounds[][]'.
Type 'Bounds' is not assignable to type 'Bounds[]'.
Property 'length' is missing in type 'Bounds'.
How do I either explicitly tell the compiler "at this point, bounds is type Bounds[] or type Bounds[][]" or use the proper if-statements so that the compiler will arrive at this conclusion on its own?