Search code examples
typescriptself-referenceobject-literal

Typescript: How to reference other prop of literal object, from within the object?


How can I self reference a prop in typescript?

const Test = {
    a: { someProp: true },
    b: { ...Test.a, someOtherProp: true } //error: Block-scoped variable 'Test' used before its declaration.

}

here is a Playground Link


Solution

  • Use a getter:

    const Test = {
        a: { someProp: true },
        get b() {
           return  { ...Test.a, someOtherProp: true }
        }
    }
    

    (This problem is not specific to TypeScript—it's how JavaScript works)