创建以函数作为值的 Map 对象

Bap*_*aud 4 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);
Run Code Online (Sandbox Code Playgroud)

我有以下错误:

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

我做错了什么吗?

Tit*_*mir 5

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

new <K, V>(entries?: ReadonlyArray<[K, V]>): Map<K, V>;
Run Code Online (Sandbox Code Playgroud)

您的数组的问题在于,它不是一个元组数组,而是一个数组数组,内部数组的一项是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;
    }],
]);
Run Code Online (Sandbox Code Playgroud)

或者使用显式类型注释:

const entityTagDictionnary: Array<[string, (e: any)=> any]> = [...]
Run Code Online (Sandbox Code Playgroud)

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

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([
]);
Run Code Online (Sandbox Code Playgroud)