Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typescript error: Object is possibly 'undefined'. when sorting array based on the contents of object map

the error is currEmot is possibly undefined. I’m confused why that is occurring because the for loop is guaranteed to loop through the emotionsObject and add objects to the map.

let emotionsObject = [
{
    size: 80,
    background: 'rgb(67, 0, 128)',
    width: .5,
    emoji: "😄",
    name: 'joy'
},
{
    size: 34,
    background: 'rgb(0, 45, 172)',
    width: .35,
    emoji: "😭",
    name: 'sadness',
},
{
    size: 50,
    background: 'rgb(172, 6, 0)',
    width: .15,
    emoji: "😡",
    name: 'anger',
},
];
type T_Emotion = typeof emotionsObject[0] 
let currEmot = new Map<string, T_Emotion>(null!);
let emotOrder: string[] = [];
for (let i = 0; i < emotionsObject.length; i++) {
   let id = uuid_v4();
   emotOrder.push(id)
   currEmot.set(id, emotionsObject[I]);
}

emotOrder.sort((a: string, b: string):number => currEmot.get(b).width - currEmot.get(a).width);

I have tried these other versions to prevent this error.

emotOrder.sort((a: string, b: string):number => currEmot?.get(b)?.width - currEmot?.get(a)?.width);
emotOrder.sort((a: string, b: string):number => currEmot.get(b).width as number - currEmot.get(a).width as number);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

use bang operator ! to tell typescript that there will be no situation where object is not found

currEmot.get(b)!.width - currEmot.get(a)!.width
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading