使TypeScript知道通过mixin在运行时添加到对象的方法

时间:2016-10-04 17:30:03

标签: javascript typescript

我正在使用第三方JavaScript库,它使用"mixin"模式向任意对象添加属性。我希望TypeScript能够在不使用继承或将其显式添加到类型定义的情况下了解这些属性。

Please enter how many lines you want: 7
0000000
 000000
  00000
   0000
    000
     00
      0

有没有办法让TypeScript识别function ThirdParty(objectToMutate: any): void { objectToMutate.newMethod = function(): void { ... } } class MyClass { ... } var myObject = new MyClass(); ThirdParty(myObject); myObject.newMethod(); 而不将myObject.newMethod()添加到newMethod而不更改MyClass?我很适合猴子补丁。

1 个答案:

答案 0 :(得分:1)

您可以定义一个由添加的方法组成的接口,然后让函数返回传入类型的函数an intersection和这个新接口:

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