ack*_*ser 11 javascript typescript
我正在一个 angular 2 cli 项目中工作,我必须在其中创建插件的定义,因为它不存在其类型。这个插件依赖于一个已经有自己的类型并且可以工作的主库。
无论如何,我有两个文件,主要的一个
库类型文件 A
export class A extends B {
constructor(...);
methodX(): void;
}
Run Code Online (Sandbox Code Playgroud)
我需要为我的插件添加一个新方法,这样我的课程就会像
export class A extends B {
constructor(...);
methodX(): void;
methodY(): void;
}
Run Code Online (Sandbox Code Playgroud)
关键是我需要将它添加到一个单独的文件中。问题是向现有类添加方法而不创建新方法
如果我把
插件类型文件 B
export class A extends B {
constructor(...);
methodX(): void;
}
Run Code Online (Sandbox Code Playgroud)
或者
插件类型文件 B
export class A extends B {
constructor(...);
methodX(): void;
methodY(): void;
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,有没有人如何实现覆盖类或使用新方法扩展它?
谢谢
tos*_*skv 12
您可以通过使用新方法创建接口并修改原型来实现。
像这样的东西:
class B { }
class A extends B {
constructor() {
super();
}
methodX(): void { };
methodY(): void { };
}
interface B {
newMethod(): void;
}
B.prototype.newMethod = function () { console.log('a') };
Run Code Online (Sandbox Code Playgroud)
这允许你在做的时候有正确的打字。
new A().newMethod();
Run Code Online (Sandbox Code Playgroud)
我在这里做了一个游乐场的例子。
Ser*_*ker 11
TypeScript 文档中的“声明合并 > 模块扩充”部分似乎提供了解决方案:
https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
在您的情况下,如果class A从 导出file1.ts,并且您想methodY()在不同的模块中添加到该类file2.ts,请尝试以下操作:
//// file1.ts
export class A extends B {
constructor(...);
methodX(): void;
}
//// file2.ts
import { A } from "./file1";
declare module "./file1" {
interface A {
methodY(): void;
}
}
A.prototype.methodY = function() {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22943 次 |
| 最近记录: |