1

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);
2
  • 3
    null! ...huh? Commented Nov 11, 2021 at 1:05
  • 1
    Where does the I come from all of the sudden? Commented Nov 11, 2021 at 1:07

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

this operator gives another warning ESLint: Forbidden non-null assertion. (@typescript-eslint/no-non-null-assertion)
you could use ?. operator instead, but I believe turning on "non-null assertion" rule in eslint is not right
?. operator gives TS2532: Object is possibly 'undefined'. This answer helped stackoverflow.com/questions/65942654/…
1

You need to creact Interface and set it to your object

interface IEmotions {
  size: number
  background: string
  width: number
  emoji: string
  name: string
}

Please keep in mind if any key could be undefined, you need to add ? to your key , for example: size?: number

let emotionsObject: (IEmotions | undefined)[] = [
 {
    size: 80,
    background: 'rgb(67, 0, 128)',
    width: .5,
    emoji: "😄",
    name: 'joy'
 }, 
 {
    size: 34,
    background: 'rgb(0, 45, 172)',
    width: .35,
    emoji: "😭",
    name: 'sadness',
 }
];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.