Circular dependency caused by importing typescript type

前端 未结 4 569
借酒劲吻你
借酒劲吻你 2020-12-20 23:40

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[]

相关标签:
4条回答
  • 2020-12-21 00:05

    You could remove the circular dependency by depending on abstractions, for example your form module could define an interface or abstract class that parent must confirm to.

    This would mean your opportunity module would depend on the form module, but not vice versa. You would inject a concrete Opportunity into the Form.parent property and that would be acceptable.

    This also allows you to define a FormParent (see below) that is a subset of Opportunity as you probably don't depend on everything in Opportunity.

    As TypeScript is structural, it is up to you whether you explicitly implement the interface on the Opportunity class.

    // opportunity.ts

    import { Form } from '....../form'
    
    export class Opportunity {
      public forms: Form[] = [];
    }
    

    // form.ts

    interface FormParent {
        forms: Form[];
    }
    
    export class Form {
      public parent: FormParent;
    }
    
    0 讨论(0)
  • 2020-12-21 00:09

    Another approach is to use require instead of import in one class.
    Looks something like:

    let LoginPage = require("./loginpage").default;
    return new LoginPage();
    

    You can find it in the Best Practice #5 from this post.

    0 讨论(0)
  • 2020-12-21 00:22

    from typescript version 3.8

    import type would help you.

    https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html

    0 讨论(0)
  • 2020-12-21 00:24

    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.

    0 讨论(0)
提交回复
热议问题