使用函数作为值创建Map对象

时间:2018-05-03 10:32:33

标签: javascript typescript

我尝试从Map词典创建string,function对象。

const entityTagDictionnary = [
  ['GRAPH_ADD_PROPERTY_SUBTYPE', (entity) => {
    console.log('addSubtype called!');
    return entity;
  }],
  ['GRAPH_IGNORE_PROPERTY_SENTENCE', (entity) => {
    console.log('ignore property called!');
    return entity;
  }],
  ['GRAPH_FORMAT_DATES', (entity) => {
    console.log('formatDates called!');
    return entity;
  }],
];

const entityMap : Map<string, Function> = new Map(entityTagDictionnary);

我收到了以下错误:

Argument of type '(string | ((entity: any) => any))[][]' isn't matching the argument 'Iterable<[string, Function]>'.

我做错了吗?

2 个答案:

答案 0 :(得分:3)

问题是要映射的构造函数采用元组数组并根据元组类型推断类型。此构造函数的签名是:

padding: 10px 0

你的数组的问题是它不是一个元组数组,它​​是一个数组数组,内部数组的项是new <K, V>(entries?: ReadonlyArray<[K, V]>): Map<K, V>; 。除非需要这样做,否则Typescript不会基于数组文字推断元组类型。简单的解决方案是将数组文字放在构造函数参数中:

string | ((e: any) => any)

或使用显式类型注释:

const entityMap: Map<string, Function> = new Map([
    ['GRAPH_ADD_PROPERTY_SUBTYPE', (entity: any) => {
        console.log('addSubtype called!');
        return entity;
    }],
    ['GRAPH_IGNORE_PROPERTY_SENTENCE', (entity: any) => {
        console.log('ignore property called!');
        return entity;
    }],
    ['GRAPH_FORMAT_DATES', (entity: any) => {
        console.log('formatDates called!');
        return entity;
    }],
]);

或者你可以使用元组助手函数强制打字脚本来推断元组类型,如here所述

const entityTagDictionnary: Array<[string, (e: any)=> any]> = [...]

答案 1 :(得分:0)

您可以尝试以下解决方法

const entityTagDictionnary: {[key:string]:Function} = {
   GRAPH_ADD_PROPERTY_SUBTYPE: (entity)=>{
    console.log('addSubtype called!');
    return entity;
   },
   ...
}

然后您根本不需要使用new Map()来电,您可以通过运行entityTagDictionnary['GRAPH_ADD_PROPERTY_SUBTYPE']('my entity')来测试它;

相关问题