Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angular - Circular dependency caused by importing typescript type

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:

  1. Define both models in the same file
  2. 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

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

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

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

1 Answer

0 votes
by (71.8m points)

You can declare a class declare class Opportunity {} in form.ts file, TypeScript will assume that class is an external class and will be available at runtime. And you can skip import in one of the class.

The only pain here is, you have to declare methods that you will be using for example,

declare class Opportunity {
     method1(): void;
     method2(): number;
}

This class will serve as simple declaration and will not require method body. And VS intellisense will work correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...