【问题标题】:How to extend and interface already set in typings?如何扩展和接口已经在类型中设置?
【发布时间】:2016-09-30 02:19:42
【问题描述】:

在 D3 中,向已经存在的 D3 变量添加属性是很常见的。

一个例子(ES5):

force = d3.layout.force()
  .nodes([{ links: 0, color: '#2BC9E9' }])

错误:

Argument of type '{ links: number; color: string; }[]' is not assignable to
parameter of type 'Node[]'.

如果我们可以创建一个新界面,我们会很简单:

interface Node_ extends Node {
    links: number;
    color: string;
}

我们如何扩展已经在 D3 的类型中定义的接口Node 以允许新的属性?

【问题讨论】:

    标签: javascript d3.js typescript


    【解决方案1】:

    Typescript 允许将接口声明拆分为多个文件。因此,您可以在代码中的任何位置添加波纹管定义

    declare namespace d3 {
        namespace layout {
            namespace force {
                interface Node {
                    links?: number;
                    color?: string;
                }
            }
        }
    }
    

    这种方式不需要新的接口定义(Node_)

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 2019-05-22
      • 2013-01-23
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多