0

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

8
  • 1
    Define an interface with optional, appropriately typed properties a and b, and declare Test an implementation of that interface. Commented Mar 18, 2020 at 20:01
  • this will end up in a huge code repetition, I have many props on the object. I will edit my question. Commented Mar 18, 2020 at 20:48
  • 2
    Which object references itself? Can you help clarify the title of this question, which is currently "Typescript: best way to construct an object that reference itself"? Right now, the object does not reference itself. It has an a property with value {someProp:true} and a b property with value {someProp:true; otherProp: true}. Nowhere does an object reference itself. Can you clarify what you need? Commented Mar 18, 2020 at 20:57
  • If your goal isn't to type it but only to make it compile, type it as any. Commented Mar 18, 2020 at 20:57
  • Define Test as { a: someType; b: someOtherType; } Define someType as { someProp: boolean; } Define someOtherType as extends someType { otherProp: boolean; } typescriptlang.org/play/index.html#code/… Commented Mar 18, 2020 at 20:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the problem with this solution is that in my real app, Test is a huge object (it's an object containing maps of typography values to keys). This solution will be enormously bloated, while it looks like typescript can potentially infer the object type automatically somehow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.