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

Joh*_*911 3 javascript typescript

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

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

第三方 index.d.ts

export as namespace thirdParty;

export Class SomeClass {
  // some methods here
}
Run Code Online (Sandbox Code Playgroud)

我的 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
}
Run Code Online (Sandbox Code Playgroud)

当调用上述现有方法时this.originalExistingMethod(),打字稿会抱怨:

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

有没有一种方法可以避免执行模块扩充时必须重新定义现有方法?

Sha*_*tin 5

初步答案

这是使用Tensorflow库的示例

扩展

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('===============');
}
Run Code Online (Sandbox Code Playgroud)

索引

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}.`);
Run Code Online (Sandbox Code Playgroud)

官方TypeScript文档中有一个类似的示例,其中增加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('===============');
}
Run Code Online (Sandbox Code Playgroud)