如何编写可自展开的TypeScript元组类型定义?
修复NodeSnapshot类型的循环引用错误并实现嵌套节点类型
你尝试定义的NodeSnapshot类型想要表示字符串或带属性的嵌套节点结构,但直接用...NodeSnapshot作为元组剩余元素会触发循环引用错误,同时也不符合TypeScript元组剩余元素的语法要求。
原错误代码
type Attributes = Record<string, string>; type NodeSnapshot = | string | [string, Attributes, ...NodeSnapshot]
错误信息
Type alias 'NodeSnapshot' circularly references itself.ts(2456)
预期匹配的示例数据
// string const s1 = 'Example Domain'; // [string, Attributes, string] const s2 = ['H1', {}, 'Example Domain']; // [string, Attributes, [string, Attributes, string]] const s3 = [ 'DIV', {}, [ 'H1', {}, 'Example Domain' ] ]; // [string, Attributes, [string, Attributes, string], string, [string, Attributes, string]] const s4 = [ 'DIV', {}, ['H1', {}, 'Example Domain'], '\n', ['A', { href: 'https://www.iana.org/domains/example' }, 'Hello, World!'], ];
解决方案
将元组中的剩余元素改为NodeSnapshot[](即NodeSnapshot的数组类型),这样既符合TypeScript元组剩余元素的语法规则,也能正确表示多个子节点的结构,同时解决循环引用问题:
type Attributes = Record<string, string>; type NodeSnapshot = | string | [string, Attributes, ...NodeSnapshot[]]
解释
在TypeScript的元组类型中,剩余元素(...T)要求T必须是数组类型。原写法中...NodeSnapshot试图将单个NodeSnapshot类型作为剩余元素,这不符合语法,同时引发了循环引用错误。改为...NodeSnapshot[]后,元组的结构明确为:标签字符串 + 属性对象 + 任意数量的子节点(每个子节点都是NodeSnapshot类型),完美匹配你给出的所有示例数据,也消除了循环引用问题。
内容的提问来源于stack exchange,提问作者Gajus
相关产品推荐
相关产品推荐

