typescript - 扩展库的类型

标签 typescript typescript-typings

我想通过两个函数扩展 bytebuffer 库 ( https://github.com/dcodeIO/bytebuffer.js ),但我在处理类型方面遇到困难(它总是说“[ts] 属性 'myNewMethod' 在类型 'ByteBuffer' 上不存在”) .

我的 bytebuffer-sc.ts (应该扩展 bytebuffer 库):

import { prototype } from 'bytebuffer';

// In the next line it says: Property 'myNewMethod' does not exist on type 'ByteBuffer'.
prototype.myNewMethod = (offset: number) => {

}

我的 src/types/bytebuffer-sc.extend.d.ts:

我尝试将“myNewMethod”添加到类型中(不幸的是没有工作):

import * as ByteBuffer from 'bytebuffer';

declare module 'bytebuffer' {
  ByteBuffer.prototype.myNewMethod: (offset: number) => number;
}

更新(第二次尝试):

import * as ByteBuffer from 'bytebuffer';

declare module 'bytebuffer' {
  export interface ByteBuffer {
    calculateVarint32: (value: number) => number;
  }
}

我的问题:

如何通过另一种方法正确扩展给定“类库”的类型?

最佳答案

您的想法是正确的,但实现方式却是错误的。

扩展类型的声明必须是:

declare module 'bytebuffer' {
    export interface ByteBuffer {
        myNewMethod: number => number;
    }
}

完成此操作后,您可以将实际方法分配给原型(prototype):

ByteBuffer.prototype.myNewMethod = (offset: number) => { };

TypeScript 需要您告诉它属性/方法存在,然后才能分配它。您混淆了声明和实际分配。

关于typescript - 扩展库的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49383140/

相关文章:

typescript - 是否可以将定义文件index.d.ts拆分为多个文件?

javascript - 在 typescript 中循环遍历文本文件

angular - Angular 中的文件输入事件类型

jquery - 如何在 typescript 类中将 jquery 插件(如 Owl Carousel 2)与 Angular 4 一起使用?

angular - TS2345 : Argument of type 'string' is not assignable to parameter of type 'never'

visual-studio - 在 Visual Studio 2015 中获取 TypeScript 以在输入和自动完成括号时自动完成

angular - 在 Angular4 库上运行 ngc 时,TsickleCompilerHost 出错

reactjs - VSCode 在 .tsx 文件中使用 AS 关键字显示类型断言错误

javascript - 如何检查对象中的值是否是原始值?

typescript - 打字中的环境依赖性和常规依赖性之间有什么区别