Skip to content

Unsound handling of unions with multiple type variables #49186

Closed

Description

@mheiber

Bug Report

🔎 Search Terms

unsound,union,generic

🕗 Version & Regression Information

  • This is a runtime error
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about: unions
    • 4.7.0-beta, 4.6.4, 4.5.5, 4.4.4, 4.2.3, 4.1.5, 4.0.5, 3.9.7, 3.8.3, 3.7.5, 3.6.3, 3.5.1, 3.3.3

⏯ Playground Link

playground link

💻 Code

Note: earlier I pasted the wrong code sample, sorry about that

function extract<K>(x: Array<K> | Array<Array<K>>): K {
  const arr = x[0];
  if (Array.isArray(arr)) {
    return arr[0];
  }
  return arr;
}

function extract2<T>(x: Array<T>): T {
  return extract(x);
}

const x = extract2([[3]]); // hover to see type: `number[]`
console.log(x); // but value is `3`
x.map(x => x); // which leads to runtime error: 'x.map is not a function'

🙁 Actual behavior

Runtime error not caught by TypeScript, due to incorrect inference.

🙂 Expected behavior

Type error.
I think extract is at fault here, but extract2 looks fishy too.

Activity

  1. whzx5byb commented on May 20, 2022

    @whzx5byb

    It works as expected after v3.6.2 in playground.

  2. MartinJohns commented on May 20, 2022

    @MartinJohns
    Contributor

    This is the behavior in every version I tried

    Which versions have you tried?

  3. RyanCavanaugh commented on May 20, 2022

    @RyanCavanaugh
    Member

    v3.3.3333

    Doing some archaeology? 😉

  4. mheiber commented on May 20, 2022

    @mheiber
    ContributorAuthor

    I've updated the code example, now there are no errors at type-checking time even on latest TS (4.7.0-beta, 4.6.4, 4.5.5, 4.4.4, 4.2.3, 4.1.5, 4.0.5, 3.9.7, 3.8.3, 3.7.5, 3.6.3, 3.5.1, and 3.3.3).

    Sorry about that, what happened was I over-reduced the example when trying on older versions. Could we re-open?

  5. mheiber commented on Jun 8, 2022

    @mheiber
    ContributorAuthor

    Update: opening as #49432. Sorry, there was a mistake in my previous repro

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

    FixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions