Circular Type References in TypeScript -


i new typescript , trying understand how can setup circular reference between 2 types. reference need not full code reference, interfaces, interfaces defined in separate files. example, let's have 2 interfaces: parent , child. doubly-linked such parent has collection of children , each child has reference parent (as seen below). how setup imports or dependencies these can defined in separate files?

interface parent {   children: child[] }  interface child {   parent: parent } 

two solutions below. prefer latter since offers clean interfacing node js modules, unfortunately ide doesn't (yet) as do...

use references

create definitions.d.ts file contain references classes/interfaces

/// <reference path="parent.ts" /> /// <reference path="child.ts" /> 

in parent.ts , child.ts, point single reference, definitions.d.ts file

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

use import...require

pass --module commonjs flag tsc import require , export want 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, not specify extension '.ts' in require

edit sept 2016

it better use es6 style imports (and avoid default exports):

parent.ts

import { child } './child'  export interface parent {      children: child[] } 

child.ts

import { parent } './parent'  export interface child {     parent: parent } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -