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 type errors don't happen sometimes in my "for..in…" code

There was no problem when testing, but sometimes the error "Cannot read properties of null (reading ‘nickname’)" occurs.
I took some of my code.

let seat = [
  null,
  null,
  { nickname: "user1", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" },
  null,
  { nickname: "user2", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" },
  null,
  null,
  null,
  null,
  null,
  null,
];
for (const i in seat) {
  if (seat[i].nickname === "user1") {
    seat[i] = null;
    break;
  }
}

console.log(seat);

I don’t know why sometimes there is no problem and suddenly an error occurs.

for (const i in seat) {
  if (seat[i] !== null && seat[i].nickname === "user1") {
    seat[i] = null;
    break;
  }
}

I temporarily solved the problem by changing the code in the form above.
I’m curious about the cause…

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 :

That’s because some of the elements in the array are null values, So you should add a condition to check that as you did seat[i] !== null but you can use the Optional chaining operator ?. as well.

FYR https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

for (const i in seat) {
  if (seat[I]?.nickname === "user1") {
    seat[i] = null;
    break;
  }
}

Ex:
If you have the data something like the one below, you don’t need to add the condition or the optional chaining operator.

let seat = [
  { nickname: "user1", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe261" },
  { nickname: "user4", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe263" },
  { nickname: "user5", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe264" },
  { nickname: "user3", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe265" },
  { nickname: "user1", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe267" },
  { nickname: "user2", uuid: "d94e81f3-df66-45f6-a593-c7ee6ccfe269" },
];
for (const i in seat) {
  if (seat[i].nickname === "user1") {
    seat[i] = null;
    break;
  }
}
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