Skip to content

Incorrect inferring of return type  #31254

Closed

Description

@cevek

Version: 3.4.5

declare function abc<T>(q: T | [{id: 'Id'}]): T 
var x = abc([{id: 'Id'}]).map(v => v.id /* 'Id' */) // string[] 

var y = abc([{id: 'Id'}]).map(v => v.id as 'Id') // 'Id'[]

Activity

  1. NN--- commented on May 4, 2019

    @NN---

    Related: #30680

    It is due to widening.
    If you want to narrow type you have to specify explicitly as you did or use some tricks.

  2. jcalz commented on May 5, 2019

    @jcalz
    Contributor

    effort level matching answer: don’t see a bug here, try SO

  3. weswigham commented on May 8, 2019

    @weswigham
    Member

    I'd refer to #241 for explaining away a return type being wider than expected

  4. added
    DuplicateAn existing issue was already created
    and removed
    BugA bug in TypeScript
    on May 8, 2019
  5. cevek commented on May 9, 2019

    @cevek
    Author

    Something strange happens here

    declare function abc<T>(q: T | {id: 'Id'}[]): T 
    var u = abc([{id: 'Id'}]) // -> {id: 'Id'}[]
    var k:{id: 'Id'}[] = u; // no problem
    var l:typeof u = k; // no problem
    var e:{id: 'Id'}[] = {} as {id: string}[]; // error (correct)
    var p = k.map(v => v.id); // -> 'Id'[]
    var t = l.map(v => v.id); // -> string[] (incorrect)
  6. weswigham commented on May 9, 2019

    @weswigham
    Member

    k's literal type isn't "fresh" since it came from a type position instead of an expression, so isn't widened. (While since l is typeof u it's still fresh)

  7. typescript-bot commented on May 11, 2019

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  8. locked as resolved and limited conversation to collaborators on Oct 21, 2025
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

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions