Skip to content

Commit 474875e

Browse files
committed
Add support for sorting literal numeric unions
Resolves #2502
1 parent 626d844 commit 474875e

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Unreleased
22

3+
### Features
4+
5+
- Literal numeric unions will now be sorted during conversion, #2502.
6+
37
### Bug Fixes
48

59
- Module readmes will now be included in JSON output, #2500.

src/lib/converter/types.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,9 +1045,10 @@ const unionConverter: TypeConverter<ts.UnionTypeNode, ts.UnionType> = {
10451045
);
10461046
},
10471047
convertType(context, type) {
1048-
return new UnionType(
1049-
type.types.map((type) => convertType(context, type)),
1050-
);
1048+
const types = type.types.map((type) => convertType(context, type));
1049+
sortLiteralUnion(types);
1050+
1051+
return new UnionType(types);
10511052
},
10521053
};
10531054

@@ -1115,3 +1116,18 @@ function kindToModifier(
11151116
return undefined;
11161117
}
11171118
}
1119+
1120+
function sortLiteralUnion(types: SomeType[]) {
1121+
if (
1122+
types.some((t) => t.type !== "literal" || typeof t.value !== "number")
1123+
) {
1124+
return;
1125+
}
1126+
1127+
types.sort((a, b) => {
1128+
const aLit = a as LiteralType;
1129+
const bLit = b as LiteralType;
1130+
1131+
return (aLit.value as number) - (bLit.value as number);
1132+
});
1133+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// A future TS version might change this so that numbers are hardcoded
2+
// to show up in a specific order. As of TS 5.3.3, this makes the union display
3+
// as 3 | 1 | 2.
4+
type WeirdOrder = [1, 2, 3][number];
5+
// ^?
6+
7+
export const Test = null! as WeirdOrder;

src/test/issues.c2.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,6 +1389,12 @@ describe("Issue Tests", () => {
13891389
convert();
13901390
});
13911391

1392+
it("Sorts literal numeric unions when converting a type, #2502", () => {
1393+
const project = convert();
1394+
const refl = query(project, "Test");
1395+
equal(refl.type?.toString(), "1 | 2 | 3");
1396+
});
1397+
13921398
it("Handles an infinitely recursive type, #2507", () => {
13931399
const project = convert();
13941400
const type = querySig(project, "fromPartial").typeParameters![0].type;

0 commit comments

Comments
 (0)