Self instantiating properties in TypeScript

It it possible to have a getter property in TypeScript that replaces itself with an instance property. I have a class with lots of metadata properties and most instances wont call them so I only want to create an instance if they are needed but I also don’t want to be calling a property with checking logic for every call after the object has been instantiated.

Something like the following snippet but strongly typed

let obj = {
  get prop() {
    delete this.prop;
    console.log('Creating instance');
    this.prop = { data: 'Here is the data' };
    return this.prop;
  }
};

console.log(obj.prop.data);

console.log(obj.prop.data);

>Solution :

One way you can do this is with Object.defineProperty, along with manually typing the getter.

const obj = {
  get prop():{data: string} {
    Object.defineProperty(this, 'prop', {
        value: { data: 'Here is the data' }
    });
    return this.prop;
  }
};

console.log(obj.prop);

You can see this typechecks on the TypeScript playground.

Leave a Reply