microsoft / microsoft/TypeScript

Use a consistent ordering when writing union types

Open
#17,944 5 comments 31 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Domain: LS: Type Display Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

In DefinitelyTyped, $ExpectType assertions depend on a type having a consistent string represenation across TypeScript versions.
It looks like the ordering of union types is dependent on some implementation details that change between versions. When we output unions as strings, we should sort them in some consistent way first instead of just using whatever order we happened to use internally.

I would suggest this ordering:

  • numeric literals, low to high
  • string literals, low to high (by <)
  • named types (including type aliases, enum, class and interface names), by name
  • function literals: by length (() => void before (x: number) => void), then by parameter name, then by parameter type
  • type literals: Sorted smallest to largest ({ x: number } before { x: number, y: number }); and type literals of the same size should be alphabetically sorted by property ({ a: number }) before { b: number }) or by the sorting of values ({ s: "a" } before { s: "b" })

Of course, another solution would be to try to handle this in $ExpectType by parsing out unions and allowing it if any sorting is valid. But it is strange in TS to see a string literal union displayed in a seemingly random order.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No file or test is named. Start by tracing the compiler path that converts union types to strings, then compare it with DefinitelyTyped $ExpectType assertions; done means union members follow a deterministic ordering across TypeScript versions.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.