Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading