Skip to content

Commit f60bd5f

Browse files
committed
Added support for zod tuple type declaration
1 parent a3ce98d commit f60bd5f

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

packages/plugins/typescript/enum-array/src/config.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,9 @@ export interface EnumArrayPluginConfig extends RawTypesConfig {
1414
* @description use enum members instead of string literals. Defaults to false
1515
*/
1616
useMembers?: boolean;
17+
/**
18+
* @description generate non-empty tuple types [EnumType, ...EnumType[]] instead of EnumType[].
19+
* Preserves original enum type in Zod parsed schemas. Defaults to false
20+
*/
21+
asNonEmptyTuple?: boolean;
1722
}

packages/plugins/typescript/enum-array/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ function buildArrayDefinition(e: GraphQLEnumType, config: EnumArrayPluginConfig)
3939

4040
if (config.constArrays) {
4141
return `export const ${upperName} = [${values}] as const;`;
42+
} else if (config.asNonEmptyTuple) {
43+
return `export const ${upperName}: [${enumName}, ...${enumName}[]] = [${values}];`;
4244
} else {
4345
return `export const ${upperName}: ${enumName}[] = [${values}];`;
4446
}

packages/plugins/typescript/enum-array/tests/enum-array.spec.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,4 +136,47 @@ describe('TypeScript', () => {
136136
`);
137137
});
138138
});
139+
140+
describe('with asNonEmptyTuple', () => {
141+
it('Should declare the array as a non-empty tuple', async () => {
142+
const schema = buildSchema(/* GraphQL */ `
143+
"custom enum"
144+
enum MyEnum {
145+
"this is a"
146+
A
147+
"this is b"
148+
B
149+
}
150+
`);
151+
const result = (await plugin(schema, [], {
152+
asNonEmptyTuple: true,
153+
})) as Types.ComplexPluginOutput;
154+
155+
expect(result.prepend).toBeSimilarStringTo(``);
156+
expect(result.content).toBeSimilarStringTo(`
157+
export const MY_ENUM: [MyEnum, ...MyEnum[]] = ['A', 'B'];
158+
`);
159+
});
160+
161+
it('Should be ignored when constArrays is true', async () => {
162+
const schema = buildSchema(/* GraphQL */ `
163+
"custom enum"
164+
enum MyEnum {
165+
"this is a"
166+
A
167+
"this is b"
168+
B
169+
}
170+
`);
171+
const result = (await plugin(schema, [], {
172+
asNonEmptyTuple: true,
173+
constArrays: true,
174+
})) as Types.ComplexPluginOutput;
175+
176+
expect(result.prepend).toBeSimilarStringTo(``);
177+
expect(result.content).toBeSimilarStringTo(`
178+
export const MY_ENUM = ['A', 'B'] as const;
179+
`);
180+
});
181+
});
139182
});

0 commit comments

Comments
 (0)