I want to populate my map, memo, with viewID for the key and an array for the value. I want to concatenate onto the array if i encounter the same viewID in my loop, however typescript is telling me preconcat is possibly undefined. I thought using the has() method would avoid this but, still the same issue. Any help?
let memo:Map<string,{}[]> = new Map<string,{}[]> ();
let total_row_count:number = 0;
for(let i = 0; i < assetLoadQuery.length; i ) {
const arrayOfPerformanceResourceTiming = JSON.parse(assetLoadQuery[i].performanceResourceTimingJSON);
const viewID:string = assetLoadQuery[i].viewID;
if(memo.has(viewID)) {
const preconcat = memo.get(viewID);
const concat = preconcat.concat(arrayOfPerformanceResourceTiming);
memo.set(viewID, concat);
} else {
memo.set(viewID, arrayOfPerformanceResourceTiming);
}
total_row_count ;
}
src/v1/metrics/asset-load.ts:50:28 - error TS2532: Object is possibly 'undefined'.
50 const concat = preconcat.concat(arrayOfPerformanceResourceTiming);
~~~~~~~~~
CodePudding user response:
you could use the non-null assertion operator.
read the docs:
A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
here is an example
CodePudding user response:
You have to assign what kind of array it is, otherwise you are just typing it as an empty array/tuple []
, so an array with 0 elements:
const memo = new Map<string,any[]>()
Replace any
with the type that it actually contains.