0

How do I do with typescript when I have a

  • Cat which has an owner: Person
  • Person which owns pet: Cat

Cat

import {Person} from './person'
export class Cat {

    owner: Person

    constructor(){
        this.owner = new Person()
    }

}

Person

import {Cat} from './cat'
export class Person {

    pet: Cat

    constructor(){
        this.pet = new Cat()
    }

}

hope there is a good solution and pattern other than workaround like having:

don't say me that typescript compiler didn't think about that case :$

Pipo
  • 4,653
  • 38
  • 47
  • 1
    Should not this `import {Person} from './cat'` be `import {Person} from './person'` – dileepkumar jami Feb 17 '19 at 13:10
  • Can you reproduce the issue in a stackblitz? I tried in [this one](https://stackblitz.com/edit/angular-q4hfnk?file=src%2Fapp%2Fapp.component.ts) but it appears to work without a problem. – ConnorsFan Feb 17 '19 at 13:51
  • TypeScript doesn't stop you from doing this, where exactly are you getting this error? TypeScript types disappear after compilation so circular dependency disappears as long as you don't instantiate or use instanceOf for each other. – Akash Kava Feb 17 '19 at 16:32
  • Thx to all, what would have helped me is to point out that when the creator of both calls a creation of the other it causes a circular dependency. (See my answer) – Pipo Feb 17 '19 at 18:43

1 Answers1

0

I find my error which was creating an instance of Cat into the Person and an instance if Person into Cat classes

So to avoid this redundency which is obviously caused by creating a

cat => which creates a Person => which creates a Cat => which creates a Person => ad eternam...

I moved the instance creation of Cat and Person

  • into a different method
  • or passing it to the constructor can do the trick too

    constructor (anOwner: Person){ this.owner = anOwner }

see stackblitz example

Pipo
  • 4,653
  • 38
  • 47