【问题标题】:How to define method on 3rd party class using typescript?如何使用打字稿在 3rd 方类上定义方法?
【发布时间】:2018-12-02 01:08:53
【问题描述】:

我正在尝试扩展第 3 方课程,但无法让 typescript 发挥出色。基本上,我不能在我的新方法中使用类中已经定义的任何现有方法。

一种解决方法是重新定义extensions.ts 中的现有方法(见下文),但必须有更好的方法。

第三者index.d.ts

export as namespace thirdParty;

export Class SomeClass {
  // some methods here
}

我的extensions.ts

import {thirdParty} from 'thirdParty'

declare module 'thirdParty' {
    namespace thirdParty {
        class SomeClass{
            newMethod(): this

            // works if I redfine the method here
            originalExistingMethod(): number
        }
    }
}

thirdParty.SomeClass.prototype.newMethod = function() {
    return this.originalExistingMethod() + 1
}

当调用像上面的this.originalExistingMethod() 这样的现有方法时,打字稿会抱怨:

TS2339: Property 'originalExistingMethod' does not exist on type 'SomeClass'

有没有办法避免在执行module augmentation时重新定义现有方法?

【问题讨论】:

  • 真正的问题是:你为什么要修改第三方类?温和地说,这是一种不好的做法。因为这是一种不好的做法,您将很难为此找到好的/正确的解决方案。

标签: javascript typescript


【解决方案1】:

初步回答

这里是 an example 使用 Tensorflow 库。

扩展.ts

import { AdadeltaOptimizer } from '@tensorflow/tfjs-core';

declare module '@tensorflow/tfjs-core' {
    interface AdadeltaOptimizer {
        newMethod(message: string): void;
    }
}

AdadeltaOptimizer.prototype.newMethod = function (message: string) {
    console.log('===============');
    console.log(message);
    console.log('===============');
}

index.ts

import { AdadeltaOptimizer } from '@tensorflow/tfjs';
import "./extend";

const optimizer = new AdadeltaOptimizer(10, 10);

// the existing method is present
const className = optimizer.getClassName();

// the augmentation is also present
optimizer.newMethod(`The className is ${className}.`);

有一个类似的例子in the official TypeScript documentation,它用map 方法扩充了Observable

跟进评论

谢谢。虽然我的问题是在定义 newMethod 时使用现有方法。所以在extend.ts 中而不是在index.ts 中。对此有何想法?

这也适用于extend.ts,如下所示:

import { AdadeltaOptimizer } from '@tensorflow/tfjs-core';

declare module '@tensorflow/tfjs-core' {
    interface AdadeltaOptimizer {
        newMethod(message: string): void;
    }
}

AdadeltaOptimizer.prototype.newMethod = function (message: string) {

    // just access the original method on `this` 
    const className = this.getClassName();

    console.log('===============');
    console.log(className);
    console.log(message);
    console.log('===============');
}

【讨论】:

  • 谢谢。虽然我的问题是在定义newMethod 时使用现有方法。所以在extend.ts 而不是index.ts。对此有何想法?
  • 这将以相同的方式工作。我会发布更新。
  • 感谢肖恩的示例回购!我克隆了它,但它仍然无法正常工作,但是......原来在纱线的缓存中有一些东西是真正的罪魁祸首!通过使用npm install 安装模块进行验证。为了解决 yarn 的问题,我运行了 yarn cache clean && yarn install 并且没有更多的 ts 错误!
  • 我很高兴听到最后的结果。很好地抓住了纱线缓存。
猜你喜欢
  • 2019-01-21
  • 1970-01-01
  • 2023-04-09
  • 2019-06-30
  • 2021-09-25
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
相关资源
最近更新 更多