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
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With