我在谷歌上搜索并使用以下 ts 代码成功扩展了 d3js 选择:
import * as d3 from "d3";
d3.selection.prototype.popover = function() {};
然后从另一个 ts 文件中使用它,例如:
(d3.select("svg").selectAll(".node") as any).popover();
这行得通,但我不喜欢这里的“any
”并且想扩展@types/d3
定义(我已经安装了@types/d3)。
我沿着函数代码 ts 文件创建了一个 d3.extend.d.ts,并写入:
/// <referencepath="../../node_modules/@types/d3-selection/index.d.ts">
declare module "d3-selection"{
export interface Selection<GElement extends BaseType, Datum, PElement extends BaseType, PDatum>{
popover();
}
}
但这似乎不起作用,如果我从调用代码中删除 any
,ts 编译器将出错。
更新:我根据答案更新了我的代码,使其成为最终的工作版本
最佳答案
您的声明合并需要使用模块的名称 - d3-selection
- 其中声明了 Selection
。像这样:
declare module "d3-selection" {
export interface Selection<
GElement extends BaseType,
Datum,
PElement extends BaseType,
PDatum
> {
popover(): void;
}
}
关于typescript - 如何编写 Typescript d.ts 文件来扩展 @types/d3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50441490/