takeradi takeradi - 1 month ago 9
TypeScript Question

Typescript const reusing property values to define new properties

Is there a way I can reuse the property value defined in an const object in Typescript to define other new properties in the same object?

Something like this:

const TEST = {
"a1": "world",
"a2": "hello",
"a3": this.a1
};


console.log(TEST.a3); logs undefined right now.

Answer

No, because TEST isn't defined yet then.
For example, if you try this:

const TEST = {
  "a1": "world",
  "a2": "hello",
  "a3": TEST["a3"]
};

You'll get:

Error: Block-scoped variable 'TEST' used before its declaration

You can do this:

const TEST = {
  "a1": "world",
  "a2": "hello"
} as { a1: string, a2: string, a3: string };

TEST.a3 = TEST.a1;

(code in playground)