首页 > 解决方案 > 创建以函数为值的 Map 对象

问题描述

我正在尝试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]>'.

我做错什么了吗?

标签: javascripttypescript

解决方案


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

new <K, V>(entries?: ReadonlyArray<[K, V]>): Map<K, V>;

您的数组的问题在于,它不是元组数组,而是数组数组,内部数组的一个项目是string | ((e: any) => any). Typescript 不会根据数组文字推断元组类型,除非需要这样做。简单的解决方案是将数组字面量放在构造函数参数中:

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;
    }],
]);

或者使用显式类型注释:

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

或者您可以使用元组辅助函数强制打字稿推断元组类型,如此处所述

function tupleArray<T1, T2, T3>(arr:[T1, T2, T3][]) : typeof arr 
function tupleArray<T1, T2>(arr:[T1, T2][]) : typeof arr 
function tupleArray<T1>(arr:[T1][]) : typeof arr 
function tupleArray(arr:any[]) : any[]{
    return arr;
}
const entityTagDictionnary = tupleArray([
]);

推荐阅读