Closed
Description
TypeScript Version: 3.6.0-dev.20190711
Search Terms: unknown narrow toString hasOwnProperty
Code
function f1(o: unknown) {
if (o) {
o.toString();
}
}
function f2(o: {}|null|undefined) {
if (o) {
o.toString();
}
}
Expected behavior:
Both succeed.
From user perspective I believe unknown behaves like an alias for the second type. So another way of looking at this problem is that given f1's signature, it's hard to explain why to someone to need to switch it to f2's signature based on whether the body needs narrowing.
Actual behavior:
f1 invalid on the toString, Object is of type 'unknown'.
Related Issues:
In this comment
#28131 (comment)
@ahejlsberg says it's a limitation of the CFA.
This bug talks about other approaches to narrowing unknown:
#25720
and in particular @Andy-MS points out a bug that feels similar:
#25720 (comment)