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
// because x: unknown
// Case 1: array object => typeof y === ‘object’
f([{ "key": "value" }])
// Case 2: array string => typeof y === ‘string’
f([‘a’])
y
is an array item, and its type isn’t specified, so TypeScript infers it asany
. Consider using Generic Types to ensure type safety and to perform operations based on the input type..The function type of the above function call will infer
function f<number>(x: number[]): void
automatically since you are passing the numbers.