【发布时间】:2018-08-03 15:55:44
【问题描述】:
尝试编写一个通用函数函数返回d3 scale。但在switch 语句后读取错误类型时出现以下错误。
import * as D3Scale from 'd3-scale';
enum scaleIdentites {
linear,
time,
}
interface ScaleProps {
scaleIdentity: scaleIdentites;
range: number[];
domain: number[];
}
export const scale = ({ scaleIdentity, domain }: ScaleProps) => {
let scaleFunction: D3Scale.ScaleLinear<number, number> | D3Scale.ScaleTime<number, number>;
switch (scaleIdentity) {
case scaleIdentites.linear:
scaleFunction = D3Scale.scaleLinear();
scaleFunction.domain([1, 2]); // correctly reads the correct type and doesnt error.
break;
case scaleIdentites.time:
scaleFunction = D3Scale.scaleTime();
scaleFunction.domain([1, 2]); // correctly reads the correct type and doesnt error.
break;
default: {
throw new Error(`Unknow scale ${scaleIdentity}`);
}
}
if (domain) {
scaleFunction.domain(domain); // error as saying should have 0 parameters.
}
};
当在case 块内时,它正确地允许我使用domain 中的参数。在它之外的错误。
【问题讨论】:
-
可能与错误无关,但
scaleTime使用Date作为域元素。或者您对 1970-01-01 之后的第一个毫秒感兴趣。您分配不返回结果的 lambda 的结果。 -
@rioV8 感谢您的提醒。尝试更改为
domain: Array<number | Date>;,但仍然出现相同的错误。似乎typescript在d3-scale类型中不断链接回domain(): number[]。当它应该看到它也可以有domain(domain: Array<number | { valueOf(): number }>): this;。我基本上不得不在各自的case语句中复制代码 -
生成的 JavaScript 是什么样子的?
-
它不会编译。
src/app/Components/D3/utils/scale.ts:55:5 - error TS2554: Expected 0 arguments, but got 1. -
scale.ts::55行的代码是什么?
标签: typescript d3.js