Skip to content

Commit

Permalink
Add support for sorting literal numeric unions
Browse files Browse the repository at this point in the history
Resolves #2502
  • Loading branch information
Gerrit0 committed Feb 26, 2024
1 parent 626d844 commit 474875e
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Unreleased

### Features

- Literal numeric unions will now be sorted during conversion, #2502.

### Bug Fixes

- Module readmes will now be included in JSON output, #2500.
Expand Down
22 changes: 19 additions & 3 deletions src/lib/converter/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1045,9 +1045,10 @@ const unionConverter: TypeConverter<ts.UnionTypeNode, ts.UnionType> = {
);
},
convertType(context, type) {
return new UnionType(
type.types.map((type) => convertType(context, type)),
);
const types = type.types.map((type) => convertType(context, type));
sortLiteralUnion(types);

return new UnionType(types);
},
};

Expand Down Expand Up @@ -1115,3 +1116,18 @@ function kindToModifier(
return undefined;
}
}

function sortLiteralUnion(types: SomeType[]) {
if (
types.some((t) => t.type !== "literal" || typeof t.value !== "number")
) {
return;
}

types.sort((a, b) => {
const aLit = a as LiteralType;
const bLit = b as LiteralType;

return (aLit.value as number) - (bLit.value as number);
});
}
7 changes: 7 additions & 0 deletions src/test/converter2/issues/gh2502.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// A future TS version might change this so that numbers are hardcoded
// to show up in a specific order. As of TS 5.3.3, this makes the union display
// as 3 | 1 | 2.
type WeirdOrder = [1, 2, 3][number];
// ^?

export const Test = null! as WeirdOrder;
6 changes: 6 additions & 0 deletions src/test/issues.c2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1389,6 +1389,12 @@ describe("Issue Tests", () => {
convert();
});

it("Sorts literal numeric unions when converting a type, #2502", () => {
const project = convert();
const refl = query(project, "Test");
equal(refl.type?.toString(), "1 | 2 | 3");
});

it("Handles an infinitely recursive type, #2507", () => {
const project = convert();
const type = querySig(project, "fromPartial").typeParameters![0].type;
Expand Down

0 comments on commit 474875e

Please sign in to comment.