递归数组类型打字稿

2023-11-23

说我有类型type Atom = string | boolean | number。我想定义一种数组类型,例如:

NestedArray = Atom | [a_0, a_1, ... , a_n]其中每个a_i is an Atom, or a NestedArray.

这可以在 Typescript 中实现吗?


类型别名无法引用自身,因此这种简单的方法将会失败:

type NestedArray = Atom | Array<NestedArray | Atom> //Type alias 'NestedArray' circularly references itself.

然而,接口可以引用自身:

interface NestedArray extends Array<NestedArray | Atom> {

}

我们可以在顶层定义一个额外的联合来处理根本情况:

type Atom = string | boolean | number

interface NestedArray extends Array<NestedArray | Atom> {

}

type AtomOrArray = Atom | NestedArray;

//Usage
let foo: AtomOrArray = [
    "",
    1, 
    [1, 2, ""]
]   

let bar: AtomOrArray =  ""
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

递归数组类型打字稿 的相关文章

随机推荐