我是打字稿的新手,我想了解如何在两种类型之间设置循环引用。引用不必是完整的代码引用,只需要接口,但接口定义在单独的文件中。例如,假设我有两个接口:Parent和Child。它们是双重关联的,因此父母有一个孩子的集合,每个孩子都有父母的参考(如下所示)。如何设置导入或依赖项以便可以在单独的文件中定义它们?
interface Parent {
children: Child[]
}
interface Child {
parent: Parent
}
答案 0 :(得分:11)
以下两种解决方案。我更喜欢后者,因为它提供了与Node JS模块的干净接口,但遗憾的是我的IDE还没有像我那样喜欢它...
使用参考
创建一个definitions.d.ts
文件,该文件仅包含对类/接口的引用
/// <reference path="Parent.ts" />
/// <reference path="Child.ts" />
在Parent.ts
和Child.ts
中,指向单个引用,definitions.d.ts
文件
/// <reference path="definitions.d.ts" />
使用import ... require
将--module commonjs
标记传递给tsc
,然后将import
传递给require
和export
您要公开的内容
在Parent.ts中
import Child = require('Child')
interface Parent {
children: Child[]
}
export = Parent
在Child.ts
import Parent = require('Parent')
interface Child {
parent: Parent
}
export = Child
请注意,您未在require
2016年9月编辑
现在最好使用ES6样式导入(并避免默认导出):
Parent.ts
import { Child } from './Child'
export interface Parent {
children: Child[]
}
Child.ts
import { Parent } from './Parent'
export interface Child {
parent: Parent
}
答案 1 :(得分:1)
我有一个循环依赖地狱中的大约10 ts文件。
通用方法已无济于事,因为10个文件之间的依赖关系非常复杂。
终于,我解决了。使用以下2种方法:
安装存储库————“循环依赖插件”:“ 5.0.2”
此回购协议将帮助我找到发生循环的地方。
使用设计好的internal.ts来管理我的进出口
我尝试了本文的方法:
How to fix nasty circular dependency issues once and for all in JavaScript & TypeScript
这篇很棒的文章告诉我创建internal.ts。
,并使用类似export * form 'file-A' ; export * from 'file-B'
的方式来管理我的循环依赖项。
当我使用与我的10个文件相关的依赖项时,例如import classA from '../internal.ts'
,效果很好。
答案 2 :(得分:1)
我也面临着类似的情况。
我可以使用pos <= 0
来解决。
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html