alexanderbird alexanderbird - 2 months ago 12
TypeScript Question

Make TypeScript aware of method added to object at runtime via mixin

I am using a third party JavaScript library that uses a "mixin" pattern to add properties to an arbitrary object. I would like TypeScript to be aware of these properties without using inheritance or adding them explicitly to the type definition.

function ThirdParty(objectToMutate: any): void {
objectToMutate.newMethod = function(): void { ... }
}

class MyClass { ... }

var myObject = new MyClass();

ThirdParty(myObject);

myObject.newMethod();


Is there a way to make TypeScript recognize
myObject.newMethod()
without adding
newMethod
to
MyClass
and without changing
ThirdParty
? I'm ok with monkey patches.

Answer

You can define an interface which consists of the added method(s), and then have the function return an intersection of the passed in type and this new interface:

interface ThirdPartyInstance {
    newMethod(): void;
}

function ThirdParty<T>(objectToMutate: T): T & ThirdPartyInstance {
    (objectToMutate as any).newMethod = function (): void {  };
    return objectToMutate as T & ThirdPartyInstance;
}

class MyClass {  }

var myObject = ThirdParty(new MyClass()); // myObject is of type MyClass & ThirdPartyInstance

myObject.newMethod();

(code in playground)