我想做这样的事:
import * as d3 from 'd3-scale-chromatic'
const selectColor = (
decimal: number,
colorScheme: string = 'interpolateRainbow'
): string =>
d3[colorScheme](decimal)但是我得到了TS错误:
元素隐式具有“任意”类型,因为“string”类型的表达式不能用于索引类型“import("PATH_TO_MODULES/node_modules/@types/d3-scale-chromatic")‘类型”
我想我基本上是想扩展我要导入的类型,比如:
interface d3 {
[key: string]: (number) => string
}发布于 2019-07-29 02:35:05
方法1:将colorScheme声明为keyof typeof d3,在调用站点将字符串类型转换为它。
type D3Scale = keyof typeof d3;
const selectColor = (
decimal: number,
colorScheme: D3Scale = 'interpolateRainbow'
): string =>
d3[colorScheme](decimal);
selectColor(1,'interpolateRainbow'); // OK
let k:string = prompt("Input method name:");
selectColor(1,k as D3Scale); // need to cast方法2:将d3转换为其索引签名。
type D3IndexType = {[k:string]:typeof d3[keyof typeof d3]};
const selectColor = (
decimal: number,
colorScheme: string = 'interpolateRainbow'
): string =>
(d3 as D3IndexType)[colorScheme](decimal)发布于 2019-07-26 10:05:17
您可以使用Conditional types并将每个colorScheme映射到其实现。
https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types
https://stackoverflow.com/questions/57207585
复制相似问题