【发布时间】:2021-06-14 14:29:28
【问题描述】:
我目前正在使用 d3.js、React 和 Typescript,在理解手动指定函数重载和消除未定义返回值的可能性的最佳方法时遇到了一些麻烦。
在下面的示例中,我尝试利用范围并使用具有以下类型的访问器函数返回 [Date, Date]。
xAccessor: (datum: Window, index: number, array: Iterable<Window>) => Date
示例用法:
const xScale = d3.scaleTime()
.domain(d3.extent<Iterable<Window>, Iterable<Date>>(data, xAccessor))
.range([0, dimensions.boundedWidth])
问题是我收到此错误消息
Argument of type '[string, string] | [undefined, undefined]' is not assignable to parameter of type 'Iterable<number | Date | { valueOf(): number; }>'.
我相信这是因为DefinitelyTyped d3 包具有以下定义。
export function extent<T, U extends Numeric>(
iterable: Iterable<T>,
accessor: (datum: T, index: number, array: Iterable<T>) => U | undefined | null
): [U, U] | [undefined, undefined];
请注意,Window 类型不允许未定义的日期。
export interface Window {
ts: Date;
high: number;
low: number;
open: number;
close: number;
volume: number;
}
const dateAccessor = (d: Window) => d.ts
我已经看到像下面这样的其他答案,您可以检查未定义并指定默认值,但我不确定如何做到这一点,并且仍然利用道具传递给子组件的访问器函数。
React, Typescript, d3js, Getting a No overload matches this call
在使用作为 props 的一部分传入的访问器时,是否有正确的方法来强制特定的重载并消除未定义结果的可能性?
【问题讨论】:
标签: javascript reactjs typescript d3.js