skip to Main Content

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?

2

Answers


  1. // because x: unknown

    // Case 1: array object => typeof y === ‘object’

    f([{ "key": "value" }])

    // Case 2: array string => typeof y === ‘string’

    f([‘a’])

    Login or Signup to reply.
  2. y is an array item, and its type isn’t specified, so TypeScript infers it as any. Consider using Generic Types to ensure type safety and to perform operations based on the input type..

    function f<T>(x: T[]) {
      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`
      }
    }
    
    f([1, 2, 4]);
    

    The function type of the above function call will infer function f<number>(x: number[]): void automatically since you are passing the numbers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search