takeradi
takeradi

Reputation: 3861

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.

Upvotes: 0

Views: 766

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164287

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)

Upvotes: 1

Related Questions