如何在 TypeScript 中创建循环引用类型? [英] How to create a circularly referenced type in TypeScript?
问题描述
我有以下代码:
type Document = number |字符串 |数组<文档>;
TypeScript 抱怨以下错误:
test.ts(7,6):错误 TS2456:类型别名文档"循环引用自身.
显然不允许循环引用.但是,我仍然需要这种结构.对此有什么解决方法?
TypeScript 的创建者解释了如何创建递归类型 此处.
循环引用的解决方法是使用extends Array
.在您的情况下,这将导致此解决方案:
type Document = number |字符串 |文档数组;接口 DocumentArray 扩展 Array{ }
更新(TypeScript 3.7)
从 TypeScript 3.7 开始,将允许使用递归类型别名,并且不再需要解决方法.请参阅:https://github.com/microsoft/TypeScript/pull/33050>
I have the following code:
type Document = number | string | Array<Document>;
TypeScript complains with the following error:
test.ts(7,6): error TS2456: Type alias 'Document' circularly references itself.
Clearly circular references are not allowed. However, I still need this kind of structure. What would be a workaround for this?
The creator of TypeScript explains how to create recursive types here.
The workaround for the circular reference is to use extends Array
. In your case this would lead to this solution:
type Document = number | string | DocumentArray;
interface DocumentArray extends Array<Document> { }
Update (TypeScript 3.7)
Starting with TypeScript 3.7, recursive type aliases will be permitted and the workaround will no longer be needed. See: https://github.com/microsoft/TypeScript/pull/33050
这篇关于如何在 TypeScript 中创建循环引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!