Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Object.defineProperty for getters in Typescript?

I have used an implementation as given below in JavaScript.

class Base {
    installGetters() {
        Object.defineProperty(this, 'add', {
            get() {
                return 5;
            }
        });
    }
}

class New extends Base {
    constructor() {
        super();
        this.installGetters();
    }

    someAddition() {
        return 10 + this.add;
    }
}

I have defined the getter property add in the function of the parent class - Base and used that property in child class New after calling the installGetters() function in the child class constructor. This works for JavaScript, but this.add is throwing an error in case of Typescript. Any help would be much appreciated.

My main motivation for doing this is that I want to pass an object to installGetters() so that it can generate multiple getters with the object keys being the getter names and the values being returned from the corresponding getter functions.

This is working in JavaScript, so my main curiosity is whether this is not possible in TypeScript or am I doing something wrong.

like image 314
Sayantan Ghosh Avatar asked Nov 15 '25 10:11

Sayantan Ghosh


1 Answers

Although this is a pretty strange pattern, I'll provide an answer to your actual question.

TypeScript is not clever enough to infer the actual Base type based on a method called on a subclass constructor, so you have to declare it:

declare readonly add: number;

TypeScript playground

like image 50
Guerric P Avatar answered Nov 18 '25 04:11

Guerric P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!