5

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
}); 
Sheph
  • 625
  • 1
  • 6
  • 19
  • `function()` declarations don't capture the `this` context, but arrow functions `=>` will. `testFunction = () => { do stuff }` [See docs](https://www.typescriptlang.org/docs/handbook/functions.html) – JBC Sep 01 '17 at 14:23

1 Answers1

8

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
}); 
Saravana
  • 37,852
  • 18
  • 100
  • 108
  • Ok, but how do I refer to `this` or the object in question in the defineProperty? It says it implicitly have type `any` (I have disallowed this in the tsconfig). – Sheph Sep 01 '17 at 14:39
  • You can specify the type of `this` as a parameter to your getter. This will be erased during compilation. – Saravana Sep 01 '17 at 14:47
  • How to put there generic type parameter ? – Renetik Jun 02 '19 at 03:01