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:
Form
interface in the Opportunity
file / the Opportunity
interface in the Form
file.Are there any other / better solutions? Thanks!
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?
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;
}
from typescript version 3.8
import type
would help you.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With