Consider a scenario where you are creating a Map from an array of objects with unique ids as keys, and then accessing the map from another array that shares the same ids:
const arr1 = [
{id: 'a', firstName: 'Mike'},
{id: 'b', firstName: 'Ben'},
{id: 'c', firstName: 'Chris'}
];
const map1 = new Map(arr1.map(element => [element.id, element]));
const arr2 = [
{id: 'b', lastName: 'Brown'},
{id: 'c', lastName: 'Clark'},
{id: 'd', lastName: 'Davis'}
];
const arr2InMap1 = arr2.filter(element => map1.has(element.id));
arr2InMap1.forEach(element => console.log(`${map1.get(element.id).firstName} ${element.lastName}`));
In a situation where "strictNullChecks" is set to true, the final line may trigger an "Object is possibly 'undefined'" error, despite it being guaranteed not to be undefined. Is there a method to inform TypeScript that the elements in the array unquestionably exist in the map?
While one can resort to using the '!' operator or crafting a function that solely returns T instead of T | undefined in place of Map.get, is there a more optimal approach to address this issue?