如何使用打字稿定义第三方类的方法?

时间:2018-11-30 22:22:47

标签: javascript typescript

我正在尝试扩展第三方课堂,但在使打字稿演奏得很好时遇到了麻烦。基本上,我不能在新方法中使用该类中已经定义的任何现有方法。

一种解决方法是重新定义# initialise class comp = recordlinkage.Compare() # initialise similarity measurement algorithms comp.string('first_name', 'name', method='jarowinkler') comp.string('lastname', 'lastname', method='jarowinkler') comp.exact('dateofbirth', 'dob') comp.exact('sex', 'sex') comp.string('address', 'address', method='levenshtein') comp.exact('place', 'place') comp.numeric('income', 'income') # the method .compute() returns the DataFrame with the feature vectors. comp.compute(candidate_pairs, census_data_1980, census_data_1990) 中的现有方法(见下文),但是必须有更好的方法。

第三方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()

执行module augmentation时是否有方法避免重新定义现有方法?

1 个答案:

答案 0 :(得分:3)

初始答案

这里是an example,使用的是Tensorflow库。

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) {
    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,它使用Observable方法扩展了map

关注评论

  

谢谢。虽然我的问题是在定义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('===============');
}