[英]How do I add a custom static method to an existing node class (e.g. Buffer) in TypeScript?
I found a solution to add a method to existing class in TypeScript.我找到了一种解决方案,可以在 TypeScript 中为现有的 class 添加方法。 I have to declare an interface with the same name and method inside it:我必须在其中声明一个具有相同名称和方法的接口:
declare interface Buffer {
foo(): string;
}
Buffer.prototype.foo = function(): string {
return "bar";
}
But what if I need to add a static method to it ( Buffer.foo
, not Buffer.prototype.foo
)?但是如果我需要向它添加一个static方法( Buffer.foo
,而不是Buffer.prototype.foo
)怎么办?
static keyword in declare interface
section is not allowed and raises an error: 'static' modifier cannot appear on a type member. ts(1070)
不允许在declare interface
部分中使用static关键字并引发错误: 'static' modifier cannot appear on a type member. ts(1070)
'static' modifier cannot appear on a type member. ts(1070)
UPD:升级版:
For @Grey:对于@灰色:
You still don't understand what am I looking for.你还是不明白我在找什么。 I need a VALID (without //@ts-ignore
) TypeScript implementation of EXACTLY this JavaScript code:我需要一个有效的(不带//@ts-ignore
) TypeScript 实现,正好是这个JavaScript代码:
// my-module/index.js
Buffer.foo = function() {
console.log("bar");
}
to let users do like this:让用户这样做:
require("my-module");
Buffer.foo();
The problem is not that I can't find an alternative .问题不在于我找不到替代品。 The problem is I can do exactly this (↑) in JavaScript but can not in TypeScript.问题是我可以在 JavaScript 中做到这一点(↑),但在 TypeScript 中不能。 Shouldn't TypeScript be absolutely compatible with JavaScript on the module-structure level at least? TypeScript 不应该至少在模块结构级别上与 JavaScript 绝对兼容吗? I mean, is it normal that I can't implement in TS a module which I can easily implement in JS?我的意思是,我不能在 TS 中实现一个我可以在 JS 中轻松实现的模块是否正常?
Yes, you can.是的你可以。 The idea is the same as you already did before.这个想法和你以前做过的一样。
Imagine we want to add a static method to Array
想象一下,我们想在Array
中添加一个 static 方法
You need to:你需要:
PoC:概念验证:
declare interface ArrayConstructor {
foo(): string;
}
Array.foo = () => `hello from static method`;
Array.foo()
For your case, it will look like对于您的情况,它看起来像
declare interface Uint8ArrayConstructor {
foo: () => string;
}
Buffer.foo()
PS TSC 3.9.6 PS TSC 3.9.6
Following your response: But I want to let users of my module (which is nothing but extension of node's Buffer) call it directly with Buffer.foo根据您的回复:但是我想让我的模块的用户(只不过是节点缓冲区的扩展)直接使用 Buffer.foo 调用它
class CustomBuffer extends Buffer {
public static foo() {
console.log('I am foo');
}
}
CustomBuffer.foo(); // I am foo
const buff = CustomBuffer.from('hello world', 'utf8');
console.log(buff); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.