Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend a typescript class with a get property?

Tags:

typescript

I get an instance of an object with say type A. How do I extend this with a getter function in Typescript? Adding a function I do

A.prototype.testFunction = function () {
  if(this.something) {
    return this.something;
  }
 return null;
}

I extend the type in an index.d.ts file such as:

interface A {
    testFunction (): SomeType|null;
}

But how am I supposed to add it if I want to to appear as a getter function, and not just as a function?

I tried looking at Object.defineProperty() but Typescript itself doesn't seem to be too happy working with that one, referring to the wrong instance of this in the following code:

Object.defineProperty(A.prototype, "testGet", {
    get: function () {
        if(this.something) { // <== this appears to not refer to type A
          return this.something;
        }
        return null;
    },
    enumerable: false,
    configurable: true
}); 
like image 622
Sheph Avatar asked Mar 09 '23 04:03

Sheph


1 Answers

Getters/setters can be declared simply as properties in interface:

interface A {
    testGet: SomeType|null;
}

And specify the type of this parameter inside the getter function:

Object.defineProperty(A.prototype, "testGet", {
    get (this: A) {
        if(this.something) { 
          return this.something;
        }
        return null;
    },
    enumerable: false,
    configurable: true
}); 
like image 106
Saravana Avatar answered Mar 11 '23 13:03

Saravana