Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference error for heterogeneous array #33664

Closed
petersolopov opened this issue Sep 29, 2019 · 4 comments
Closed

Type inference error for heterogeneous array #33664

petersolopov opened this issue Sep 29, 2019 · 4 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@petersolopov
Copy link

Search Terms: Generic, Heterogeneous Array

Code

function shuffleArray<I>(array: I[]): I[] {
  return (
    array
      .map(item => [Math.random(), item])
      .sort((a, b) => a[0] - b[0])
      .map(item => item[1])
  );
}

Expected behavior: no error

Actual behavior: error

Type '(number | I)[]' is not assignable to type 'I[]'.
  Type 'number | I' is not assignable to type 'I'.
    'number | I' is assignable to the constraint of type 'I', but 'I' could be instantiated with a different subtype of constraint '{}'.
      Type 'number' is not assignable to type 'I'.
        'number' is assignable to the constraint of type 'I', but 'I' could be instantiated with a different subtype of constraint '{}'.

Playground Link: http://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABAZwBYmMANgUwIIBOBAhgJ4A8AkgHwAUxRZAXIpQNoC6AlC+x4gG8AUIkQEcUEASS0RoxAxKk58xADoAtsQAOtGFBwbEAXmqI2AWWJRUakmAAmcDbS4AaRPsPcV8tcjgCKFp6DwAjLhMzYjYABn4AWkQwuJ9VUU0dPQMjU08ctgBGNMQuAG4hAF8gA

P.S Flow works fine

@jablko
Copy link
Contributor

jablko commented Sep 29, 2019

Does adding as const help? e.g.

.map(item => [Math.random(), item] as const)

@petersolopov
Copy link
Author

@jablko Yes, thanks! But I still think It should work without this feature

@MartinJohns
Copy link
Contributor

It does, if you're explicit with the types:

.map<[number, I]>(item => [Math.random(), item])

By default array-literals are inferred as arrays, so you return an array that has either a number or a I. Changing this to automatically infer as tuples would very likely be a breaking change. And we already have a way to tell the compiler to infer it as a tuple: as const.

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Sep 29, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

5 participants