【问题标题】:How to augment d3-selection module in TypeScript?如何在 TypeScript 中增加 d3-selection 模块?
【发布时间】:2020-01-09 23:56:32
【问题描述】:

我有一个使用 TypeScript 和 d3 的项目。我已经安装了 'd3'、'@types/d3' 并像这样使用 d3:

import * as d3 from 'd3';
const x = d3.scaleLinear ...

在我想使用未在当前“@types/d3-selection”中声明的d3.scaleSymlog 之前,它运行良好。

我尝试扩充“d3-selection”模块:

declare module 'd3-selection' {
  export function scaleSymlog(...);
}

但是在这样做之后,我的代码中使用的 'd3-selection' 甚至其他 d3 子模块中的所有符号现在都找不到了:

Property 'mouse' does not exist on type 'typeof import("<project>/frontend/node_modules/@types/d3/index")'.

TypeScript 文档说:

You can’t declare new top-level declarations in the augmentation – just patches to existing declarations.

那么,我该如何正确声明和使用scaleSymlog

【问题讨论】:

    标签: typescript d3.js typescript-typings


    【解决方案1】:

    您确定d3-selection 导出此方法吗?

    使用您提供的代码似乎可以正确地扩充 @types 包。可能检查您的 TypeScript 版本或tsconfig 设置?

    另外,您确定类型是错误吗?测试它会产生运行时错误,因为 scaleSymlog 不是函数。

    import { scaleSymlog, select } from "d3-selection";
    
    declare module "d3-selection" {
      export function scaleSymlog(something: number);
    }
    
    // scaleSymlog(1) <-- Runtime error
    // select("something") <-- Still valid
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 2017-12-07
      相关资源
      最近更新 更多