在TypeScript中动态访问导入的模块的方法

时间:2019-07-25 17:45:16

标签: d3.js typescript-typings typescript2.0 typescript-generics

我正在尝试做这样的事情:

import * as d3 from 'd3-scale-chromatic'

const selectColor = (
    decimal: number, 
    colorScheme: string = 'interpolateRainbow'
): string => 
    d3[colorScheme](decimal)

但是我遇到了这个TS错误:

  

元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型“ typeof import(“ PATH_TO_MODULES / node_modules / @ types / d3-scale-colour”)'

思考我基本上想用一些类似的东西扩展我要导入的类型:

interface d3 {
    [key: string]: (number) => string
}

2 个答案:

答案 0 :(得分:0)

您可以在Conditional types周围玩耍,并将每个colorScheme映射到其实现。

https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types

答案 1 :(得分:0)

方法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)