如何使Typescript识别递归类型而不落在字符串上

时间:2021-02-09 16:55:24

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:

我需要编写一个Typescript程序,将数字树建模为嵌套数组。意思是,当某个叶子不是数字时,它应该给出一个错误,但是例如boolean或string。我写了代码:

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

它按预期工作,有四个编译错误。前两个因为true不是数字,后两个因为该值不是数组。不幸的是,代码

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.

编译,尽管“abc”叶子既不是数字也不是树的数组。不知何故,字符串被识别为递归类型。有没有办法让Typescript看到问题?也许不同的树定义,或其他什么?我知道我可以使用typeof在JS中轻松解决它,但我需要Typescript(意思是静态)解决方案。谢谢。

1 个解决方案

#1


2  

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;
}

#1


2  

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;
}