相关疑难解决方法(0)

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

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

一种解决方法是重新定义中的现有方法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'

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

javascript typescript

3
推荐指数
1
解决办法
501
查看次数

标签 统计

javascript ×1

typescript ×1