[英]Is there a good way of telling typescript all array elements exist in a Map?
Let's say I'm creating a Map from an array of objects with ids as keys, then accessing the map from a different array that has the same ids:假设我正在从以 id 作为键的对象数组创建 Map,然后从具有相同 id 的不同数组访问 map:
const arr1 = [
{id: 'a', firstName: 'Jeff'},
{id: 'b', firstName: 'John'},
{id: 'c', firstName: 'Jeremy'}
];
const map1 = new Map(arr1.map(element => [element.id, element]));
const arr2 = [
{id: 'b', lastName: 'Johnson'},
{id: 'c', lastName: 'Jackson'},
{id: 'd', lastName: 'Jenkins'}
];
const arr2InMap1 = arr2.filter(element => map1.has(element.id));
arr2InMap1.forEach(element => console.log(`${map1.get(element.id).firstName} ${element.lastName}`));
If I have "strictNullChecks": true, then the final line would throw an "Object is possibly 'undefined'" error, even though it can never be undefined.如果我有“strictNullChecks”:true,那么最后一行会抛出一个“对象可能是'未定义'”错误,即使它永远不会是未定义的。 Is there a way of telling typescript that the elements in the array exist in the map?有没有办法告诉 typescript 数组中的元素存在于 map 中?
I know I can use the ',' operator.我知道我可以使用“,”运算符。 or create a function that only returns T instead of T |或创建只返回 T 而不是 T | 的 function | undefined to replace Map,get?未定义替换 Map,明白吗? but is there a better way of achieving this?但是有没有更好的方法来实现这一点?
No, that is the signature for Map.get
.不,这是Map.get
的签名。 If this is bothersome, a plain object might work better for your case:如果这很麻烦,简单的 object 可能更适合您的情况:
const obj1 = arr1.reduce(
(obj, value) => (obj[value.id] = value) && obj,
{} as Record<string, typeof arr1[number]>,
);
const arr2InMap1 = arr2.filter(element => element.id in obj1);
arr2InMap1.forEach(element => console.log(`${obj1[element.id].firstName} ${element.lastName}`));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.