我有以下代码:
type Document = number | string | Array<Document>;
TypeScript出现以下错误:
test.ts(7,6): error TS2456: Type alias 'Document' circularly references itself.
显然,循环引用是不允许的.然而,我仍然需要这种 struct .解决这个问题的方法是什么?
我有以下代码:
type Document = number | string | Array<Document>;
TypeScript出现以下错误:
test.ts(7,6): error TS2456: Type alias 'Document' circularly references itself.
显然,循环引用是不允许的.然而,我仍然需要这种 struct .解决这个问题的方法是什么?
TypeScript的创建者解释了如何创建递归类型here.
循环引用的解决方法是使用extends Array
.在您的情况下,这将导致以下解决方案:
type Document = number | string | DocumentArray;
interface DocumentArray extends Array<Document> { }
Update (TypeScript 3.7)
从TypeScript 3.7开始,将允许使用递归类型别名,不再需要解决方法.见:https://github.com/microsoft/TypeScript/pull/33050