了解打字稿定义

时间:2019-05-30 11:49:11

标签: typescript d3.js

@types/d3定义中,各行如下:

export type ValueFn<T extends BaseType, Datum, Result> = (this: T, datum: Datum, index: number, groups: T[] | ArrayLike<T>) => Result;

attrTween(name: string): ValueFn<GElement, Datum, (t: number) => string> | undefined;

当我使用函数attrTween时,我会像这样使用它:

caller.attrTween("points", (d, index, groups) => { return (t) => {return "";};  }

呼叫者为Transition<BaseType, PieArcDatum<number>

这些参数由VSCode推断为:

(parameter) d: d3.PieArcDatum<number>
(parameter) index: number
(parameter) groups: d3.BaseType[] | d3.ArrayLike<d3.BaseType>

类型定义如何强制执行此行为? 可以逐字解释,特别是 通用 用法吗?

1 个答案:

答案 0 :(得分:2)

attrTween具有three separate overloads,其中第三个条目(只有带有非空第二个参数的两个参数重载)是:

/**
 * Assign the attribute tween for the attribute with the specified name to the specified interpolator factory.
 * An interpolator factory is a function that returns an interpolator; when the transition starts, the factory is evaluated for each selected element.
 * The returned interpolator will then be invoked for each frame of the transition, in order,
 * being passed the eased time t, typically in the range [0, 1]. Lastly, the return value of the interpolator will be used to set the attribute value.
 * The interpolator must return a string.
 *
 * @param name Name of attribute.
 * @param factory An interpolator factory which is evaluated for each selected element, in order, being passed the current datum (d),
 * the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The interpolator factory returns a string interpolator,
 * which takes as its argument eased time t, typically in the range [0, 1] and returns the interpolated string.
 */
attrTween(name: string, factory: ValueFn<GElement, Datum, (t: number) => string>): this;

与您列出的过载相比,它与您的呼叫的匹配要好得多。此定义存在于“过渡”中,定义如下:

export interface Transition<GElement extends BaseType, Datum, PElement extends BaseType, PDatum>

有了这个,我们可以看到直接映射:

  • dDatum,而caller中的d3.PieArcDatum<number>
  • indexnumber
  • groupsT[] | ArrayLike<T>,其中T extends BaseType
    • 根据attrTween的定义,T中的ValueFnGElement中的Transition相同。
    • GElementBaseType中的callee
    • 因此,TBaseType,所以groupsd3.BaseType[] | d3.ArrayLike<d3.BaseType>