Skip to content

unknown should be narrowable to {} #32347

Closed
@evmar

Description

@evmar

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'.

Playground Link:
http://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABMAjACjgLkeA1mOAdzAEpEBvAKEURmEQzKpprgDoo4BlKAJxjABzNCQDc1RAF9K00JFgJkAJgzZykgD5gQAGx0bwAEwCmwAccNMJdBnCstE7Tj35CR4mtMlA

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fix AvailableA PR has been opened for this issueIn DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions