TypeScript 中的循环类型引用 [英] Circular Type References in TypeScript
问题描述
我是打字稿的新手,正在尝试了解如何在两种类型之间设置循环引用.引用不需要是完整的代码引用,只需是接口,而是在单独的文件中定义接口.例如,假设我有两个接口:Parent 和 Child.它们是双重链接的,这样父级有一个子级集合,每个子级都有一个对父级的引用(如下所示).如何设置导入或依赖项,以便可以在单独的文件中定义它们?
I am new to typescript and am trying to understand how I can setup a circular reference between two types. The reference need not be a full code reference, simply the interfaces, but with interfaces defined in separate files. For example, let's say I have two interfaces: Parent and Child. They are doubly-linked such that the parent has a collection of children and each child has a reference to the parent (as seen below). How do I setup the imports or dependencies so that these can be defined in separate files?
interface Parent {
children: Child[]
}
interface Child {
parent: Parent
}
推荐答案
下面有两个解决方案.我更喜欢后者,因为它提供了与 Node JS 模块的干净接口,但不幸的是,我的 IDE(还)不像我那样喜欢它......
Two solutions below. I prefer the latter since it offers clean interfacing with Node JS modules, but unfortunately my IDE doesn't (yet) like it as much as I do...
使用引用
创建一个 definitions.d.ts
文件,该文件将只包含对您的类/接口的引用
Create a definitions.d.ts
file that will only contain the references to your classes/interfaces
/// <reference path="Parent.ts" />
/// <reference path="Child.ts" />
在Parent.ts
和Child.ts
中,指向一个引用,definitions.d.ts
文件
In Parent.ts
and Child.ts
, point to a single reference, the definitions.d.ts
file
/// <reference path="definitions.d.ts" />
使用 import...require
将 --module commonjs
标志传递给 tsc
然后 import
你require
和 export
你想暴露什么
pass the --module commonjs
flag to tsc
then import
what you require
and export
what you want to expose
在 Parent.ts 中
In Parent.ts
import Child = require('Child')
interface Parent {
children: Child[]
}
export = Parent
在 Child.ts 中
In Child.ts
import Parent = require('Parent')
interface Child {
parent: Parent
}
export = Child
请注意,您没有在 require
这篇关于TypeScript 中的循环类型引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!