alexanderbird alexanderbird - 10 months ago 74
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();



Is there a way to make TypeScript recognize
without adding
and without changing
? I'm ok with monkey patches.

Answer Source

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


(code in playground)