I'm modeling data in typescript sent from a server to my Angular app. An Opportunity
has a forms
property containing an array of Form[]
objects. A Form
has a parent
property which may contain an Opportunity
. In order to resolve the types, the file which defines Opportunity
imports Form
and the file which defines Form
imports Opportunity
. This creates a circular dependency warning.
I've found several prior SO questions dealing with circular dependencies (here, here), but in each case they were dealing with circular dependencies in the javascript code. In this case, the circular dependency is only with the typescript types, and will not exist after compilation. Is there some way to include a type in a file while avoiding this circular dependency issue? So far I haven't found anything.
I can think of two solutions to this problem:
- Define both models in the same file
- Recreate the
Form
interface in the Opportunity
file / the Opportunity
interface in the Form
file.
Are there any other / better solutions? Thanks!
Update 2
I appear to have found an answer (it was just really far down in the list of questions for some reason). This answer suggestions two possibilities
Create a seperate definition file (which would seem to involve recreating the Opportunity
and Form
class interfaces, so would be no better then option #2 above).
Use import, which is what I'm already doing (and which is causing the circular dependency warning).
Is there a way to import just the associated interface of a class?
Update 3
Just to be clear, currently Opportunity
and Form
look like this:
// opportunity.ts
import { Form } from '....../form'
export class Opportunity {
public forms: Form[] = [];
}
// form.ts
import { Opportunity } from '....../opportunity'
export class Form {
public parent: Opportunity;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…