niryo
niryo

Reputation: 1565

Typescript: best way to construct an object that reference itself

I am trying to migrate this simplified js code into ts:

let Test = {};
Test.a = { //error: prop a does not exist
    someProp: true
};

Test.b = {
    ...Test.a,//self referencing
    otherProp: true
};

export default Test;

I want to avoid extracting the object to an interface, because the object has many props and I don't want to repeat all the props in the implementation.

Any suggestions?

Playground Link

Upvotes: 0

Views: 641

Answers (1)

Evert
Evert

Reputation: 99728

The result should still be correctly inferred when you re-arrange things a bit.

const a = {
    someProp: true
}
const b = {
    ...a,
    otherProp: true
}

const test = {a, b}

export default test;

The 'trick' to building up an object like this, is that you need to construct it all at once and not modify it in multiple steps. By reversing the order you achieve this.

Upvotes: 1

Related Questions