TypeScript Module Augmentation - Reference to Full Instance as 'this' instead of subproperty

Viewed 75

I want to extend a class from some library by adding my own utility functions under the util property to it. (Written in TypeScript, using module augmentation)

When I call my methods like so: someClassInstance.util.doSomething(), they do not receive the full someClassInstance, but only the property util, which we already know.

However, these functions need the values from each SomeClass instance when called.

Is there a way to receive the upper scope (someClassInstance) instead of someClassInstance.util as this?

I know it would be easier to implement just passing in the instance as a parameter to the function, but that would make consuming my methods not as nice, as you'd effectively be repeating yourself (someClassInstance.util.doSomething(someClassInstance) contains the instance twice)

import * as exported from './[SAME_FILE]';
import { SomeClass } from 'SomeLibrary';

declare module 'SomeLibrary' {
    interface SomeClass {
        util: typeof exported;
    }
}

SomeClass.prototype.util = exported;

// Does not work, expects an instance of SomeClass, 
// but can only receive SomeClass.util
export async function doSomething(this: SomeClass) {
    // do something with `this` (= someClassInstance)
}

Example Implementation

0 Answers
Related