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

Casting array to union + mapped array types not preserving type order #31283

Closed
samdenty opened this issue May 7, 2019 · 1 comment
Closed
Labels
Question An issue which isn't directly actionable in code

Comments

@samdenty
Copy link

samdenty commented May 7, 2019

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:

Mapped types key order lost

Code

type Initial = [1, 2, 3, 4]

type FindReplace<T extends any[], Find, Replace> = {
  [K in keyof T]: T[K] extends Find ? Replace : T[K]
}

// Map over array and replace '2'
type ResultArray = FindReplace<Initial, 2, 'was 2'>
// => [1, "was 2", 3, 4]

// Now accessing the array values using [number], the type
// order is lost. This matters because now when the union is later
// cast as a intersection, the types are in the wrong order
type Result = ResultArray[number]
// => 1 | 3 | 4 | "was 2

Expected behavior:

Mapping over types should preserve the key order

Actual behavior:

Mapping over types preserves the "type", but the key order is lost when performing T[keyof T] operator

Related Issues:

@dragomirtitian
Copy link
Contributor

Union order is not something that you should count on for anything. @RyanCavanaugh mentioned this when unions to tuples were discusses here:

First, union order is not something we can ever allow to be observable. Internally, unions are stored as a sorted list of types (this is the only efficient way to quickly determine relationships between them), and the sort key is an internal ID that generated incrementally. The practical upshot of this is that two extremely similar programs can generate vastly different union orderings, and the same union observed in a language service context might have a different ordering than when observed in a commandline context, because the order in which types are created is simply the order in which they are checked.

@weswigham weswigham added the Question An issue which isn't directly actionable in code label May 8, 2019
@samdenty samdenty closed this as completed May 9, 2019
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

3 participants