Circular dependency caused by importing typescript type

前端 未结 4 580
借酒劲吻你
借酒劲吻你 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;
    }
    

提交回复
热议问题