Viper Bailey Viper Bailey - 2 months ago 40
TypeScript Question

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
}

Answer

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

EDIT Sept 2016

It is now better to use ES6 style imports (and avoid default exports):

Parent.ts

import { Child } from './Child'

export interface Parent { 
    children: Child[]
}

Child.ts

import { Parent } from './Parent'

export interface Child {
    parent: Parent
}
Comments