Skip to content

unknown should be narrowable to {} #32347

Closed

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)
Anders Hejlsberg (@ahejlsberg) says it's a limitation of the CFA.

This bug talks about other approaches to narrowing unknown:
#25720
and in particular Andy (Andrewkraft) (@Andy-MS) points out a bug that feels similar:
#25720 (comment)

Activity

  1. added
    Awaiting More Feedback
    Suggestion
    on Jul 31, 2019
  2. taralx commented on Apr 5, 2022

    @taralx

    Also running into this when dealing with JSON, as the result of unmarshaling is reasonably unknown, and result ? result.toString() : "" doesn't type check...

  3. DanielRosenwasser commented on May 18, 2022

    @DanielRosenwasser
    Member

    PR is out at #49119

  4. added
    In Discussion
    and removed
    Awaiting More Feedback
    on May 18, 2022
  5. added
    Fix Available
    on May 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fix AvailableIn DiscussionSuggestion

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions