Closed
Description
Bug Report
I found a curious situation in Typescript 4.8 where a variable of type unknown
narrowed down to {}
behaves differently than a variable of type {}
from the beginning.
🔎 Search Terms
4.8, narrow, in
Not sure if it is related to #50527.
🕗 Version & Regression Information
- I was unable to test this on prior versions because it relies on a new 4.8 feature.
⏯ Playground Link
Playground link with relevant code
💻 Code
const f = (x: {}, y: unknown) => {
if (!("a" in x)) {
return;
}
console.log(x);
// x stays {} (is not narrowed), not optimal but at least not wrong
if (!y) {
return;
}
// y is narrowed to {}
if (!("a" in y)) {
return;
}
console.log(y);
// y is narrowed to never, which is clearly incorrect, and pretty strange because
// it had the same type as x before and we run the same guard
}
🙁 Actual behavior
Narrowing unknown
to {}
and then using the in
operator results in an incorrect type, whereas it doesn’t happen when starting with a variable of type {}
.
🙂 Expected behavior
Narrowing should behave the same way whether we start with the type {}
or narrow unknown
down to {}
.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment