我想通过两个函数扩展 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/