d3.js - 了解 Typescript 定義
從 @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
`attrTween` 有三個不同的重載,其中第三個項目(也是唯一一個擁有非空第二參數的雙參數重載)是:
/**
* 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;
這比你列出的多載版本更符合你的呼叫。此定義存在於 Transition 中,該過程定義如下:
export interface Transition<GElement extends BaseType, Datum, PElement extends BaseType, PDatum>
由此,我們可以看到直接對應關係:
d是Datum,它從caller來,是d3.PieArcDatum<number>index是numbergroups是T[] | ArrayLike<T>,其中T extends BaseType。- 根據
attrTween的定義,ValueFn中的T與Transition中的GElement相同。
- 根據
GElement根據你的callee是BaseType。- 因此
T是BaseType,所以groups是d3.BaseType[] | d3.ArrayLike<d3.BaseType>,如你所見。
