Typescript: type narrowing on an object array

  Kiến thức lập trình

I have this code:

const f = (x: unknown) => {
  if (!x || !Array.isArray(x)) {
    throw new Error("bad");
  }

  for (const y of x) {
    if (!y || typeof y !== "object") {
      throw new Error("bad");
    }

    y // y does intellisense think this has type `any`
  }
};

In my VS Code, intellisense thinks the final y has type any. I would expect it to have type object. Why is this? And how should I structure my code so that intellisense recognizes the second y has type object?

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT