javascript - 创建以函数为值的 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]>'.
我做错什么了吗?
解决方案
问题是要映射的构造函数采用元组数组并根据元组类型推断类型。此构造函数的签名是:
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([
]);
推荐阅读
- javascript - JS删除类显示无不起作用
- python - 如何使用 fmri 数据理解 sns.distplot 图表
- java - Lombok EqualsAndHashCode 与继承
- rust - 为什么在可变变量上调用方法会导致其值被移动?
- c# - 如何使用存储过程更新现有行并插入新行?
- vb.net - 如何创建仅在需要时修改的列表的引用?
- java - 如何找到二维数组中所有元素的总和?
- node.js - 使用 Express 提供静态文件还是使用 Express 仅访问后端?
- php - 将 ALT 属性替换为图片标题 + ACF 关系 URL(如果存在)
- winapi - 是否有与 NtSetInformationFile 等效的用户空间?