I can't seem to understand why typescript has an issue with the code below. The errors from the compiler are detailed in the comments within the code.
const FOO = Symbol();
function bar<T>(param: T) {
if (param !== null && typeof param === "object" && FOO in param) {
// Element implicitly has an 'any' type because expression of type 'unique symbol' can't be used to index type 'unknown'.
// Property '[FOO]' does not exist on type 'unknown'.ts(7053)
const foo = param[FOO];
console.log(foo);
}
}
function bar2<T>(param: T) {
if (param !== null && typeof param === "object" && "FOO" in param) {
// Element implicitly has an 'any' type because expression of type '"FOO"' can't be used to index type 'unknown'.
// Property 'FOO' does not exist on type 'unknown'.ts(7053)
const foo = param["FOO"];
console.log(foo);
}
Don't you think the if
statement should narrow down the type sufficiently?