Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

Circular Type References in TypeScript

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
}
question from:https://stackoverflow.com/questions/24444436/circular-type-references-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...

Use references

Create a definitions.d.ts file that will only contain the references to your classes/interfaces

/// <reference path="Parent.ts" />
/// <reference path="Child.ts" />

In Parent.ts and Child.ts, point to a single reference, the definitions.d.ts file

/// <reference path="definitions.d.ts" />

Use import...require

pass the --module commonjs flag to tsc then import what you require and export what you want to expose

In Parent.ts

 import Child = require('Child')

 interface Parent { 
     children: Child[]
 }

 export = Parent

In Child.ts

 import Parent = require('Parent')
 
 interface Child {
     parent: Parent
 }

 export = Child

Please note, that you do not specify the extension '.ts' in require


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...