Akash Vishwakarma
Akash Vishwakarma

Reputation: 177

how to fix circular dependency in TypeScript

foo has a bar type values and bar has foo type value as a meal, it is showing error that

[ts] Block-scoped variable 'foo' used before its declaration. [2448]

const bar = {
            meal: foo,      //  ¯\_(ツ)_/¯!
            sweet: true,
            sassy: false,
};

const foo = {
            beer : 0,
            vodka : false,
            redwine: -1,
            taste: [bar]
};

Upvotes: 0

Views: 416

Answers (2)

Zakaria Chabihi
Zakaria Chabihi

Reputation: 56

Try this:

const bar = {
            sweet: true,
            sassy: false,
};

const foo = {
            beer : 0,
            vodka : false,
            redwine: -1,
            taste: []
};
bar.meal = foo;
foo.taste[0] = bar;

EDIT 1: Make the code compliant with the typing system

type barType = {
    sweet: boolean,
    sassy: boolean,
    meal: fooType
};
type fooType = {
    bear: number,
    vodka: boolean,
    redwine: number,
    taste: barType[]
};
const foo: fooType = {
    bear : 0,
    vodka : false,
    redwine: -1,
    taste: []
};
const bar: barType = {
    sweet: true,
    sassy: false,
    meal: foo
};
foo.taste[0] = bar;

Upvotes: 0

deceze
deceze

Reputation: 522081

This has little to do with any types, just add one object to the other after it's all constructed:

const foo = {
  bear: 0,
  vodka: false,
  redwine: -1,
  taste: []
};

const bar = {
  meal: foo,
  sweet: true,
  sassy: false,
};

foo.taste.push(bar);

Upvotes: 1

Related Questions