Sheph
Sheph

Reputation: 675

How to extend a typescript class with a get property?

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

Upvotes: 6

Views: 2120

Answers (1)

Saravana
Saravana

Reputation: 40594

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

Upvotes: 8

Related Questions