I need to write a Typescript program that models numbers tree as nested array. Meaning, it should give an error when some leaf is not a number, but for example boolean or string. I wrote the code:
interface Tree {
[index: number]: number | Tree;
}
let a:Tree = [1, 3, [4, 8, [], 5, 9, true, [[[0]]]]];
let b:Tree = [true];
let c:Tree = true;
let d:Tree = 3;
and it works as expected, with four compilation errors. First two because true is not a number, last two because the value is not an array. Unfortunately, the code
interface Tree {
[index: number]: number | Tree;
}
let e:Tree = [1, 3, [4, 8, [], 5, 9, "abc", [[[0]]]]];
let f:Tree = ["abc"];
let g:Tree = "abc";
compiles, despite "abc" leaf is neither a number nor an array of Trees. Somehow, string is recognized as recursive type. Is there a way to make Typescript to see the problem? Maybe different Tree definition, or something else? I know I can solve it easily in JS, using typeof, but I need Typescript (meaning, static) solution. Thank you.