Skip to content

Commit e07a58f

Browse files
committed
feat: add getValues function for extracting literal values from TypeScript types
1 parent 61afdf8 commit e07a58f

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

src/util/values.util.ts

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import ts, { NumberLiteralType, StringLiteralType } from "typescript";
2+
import { LiteralValue } from "@code0-tech/sagittarius-graphql-types";
3+
4+
/**
5+
* Extracts literal values from a TypeScript type.
6+
*
7+
* This function recursively processes TypeScript types and extracts all literal values,
8+
* including string literals, number literals, and boolean literals. For union types,
9+
* it flattens and combines all literal values from each constituent type.
10+
*
11+
* @param type - The TypeScript type to extract values from
12+
* @returns An array of LiteralValue objects representing all literal values found in the type
13+
*
14+
* @example
15+
* // For a type like "red" | "blue" | 42
16+
* const values = getValues(type);
17+
* // Returns:
18+
* // [
19+
* // { value: "red", __typename: "LiteralValue" },
20+
* // { value: "blue", __typename: "LiteralValue" },
21+
* // { value: "42" }
22+
* // ]
23+
*/
24+
export const getValues = (type: ts.Type): LiteralValue[] => {
25+
// Handle union types by recursively extracting values from each constituent type
26+
if (type.isUnion()) {
27+
return type.types.flatMap(getValues);
28+
}
29+
30+
// Extract string literal values
31+
if (type.isStringLiteral()) {
32+
return [
33+
{
34+
value: (type as StringLiteralType).value,
35+
__typename: "LiteralValue",
36+
},
37+
];
38+
}
39+
40+
// Extract number literal values, converting to string representation
41+
if (type.isNumberLiteral()) {
42+
return [
43+
{
44+
value: (type as NumberLiteralType).value.toString(),
45+
},
46+
];
47+
}
48+
49+
// Extract boolean true literal values
50+
if ((type as any).intrinsicName === "true") {
51+
return [
52+
{
53+
value: "true",
54+
__typename: "LiteralValue",
55+
},
56+
];
57+
}
58+
59+
// Extract boolean false literal values
60+
if ((type as any).intrinsicName === "false") {
61+
return [
62+
{
63+
value: "false",
64+
__typename: "LiteralValue",
65+
},
66+
];
67+
}
68+
69+
// Return empty array if no literal values are found
70+
return [];
71+
};

0 commit comments

Comments
 (0)