1

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.

1 Answer 1

3

It happens because when accessing an object, numerical keys are treated as if they where strings. You can do the following to constrain the value of the properties though:

interface Tree {
    [key: number]: Array<Tree | number> | number;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your help, it works perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.