search

Home  >  Q&A  >  body text

In my "for..in..." code, sometimes TypeScript type errors don't appear

There is no problem when testing, but sometimes the error "Cannot read property of null (read 'nickname')". I posted part of the 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, but suddenly there is an error.

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 to the above form. I'm curious as to why...

P粉166779363P粉166779363475 days ago541

reply all(1)I'll reply

  • P粉903969231

    P粉9039692312023-09-10 00:29:02

    This is because some elements in the array are null, so you should add a condition to check, like you did seat[i] !== null, but you can also use Optional chaining operator ?..

    Reference:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining

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

    Example: If your data looks like below, you don't need to add conditional or optional chaining operators.

    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;
      }
    }

    reply
    0
  • Cancelreply