Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/plugins/typescript/enum-array/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,9 @@ export interface EnumArrayPluginConfig extends RawTypesConfig {
* @description use enum members instead of string literals. Defaults to false
*/
useMembers?: boolean;
/**
* @description generate non-empty tuple types [EnumType, ...EnumType[]] instead of EnumType[].
* Preserves original enum type in Zod parsed schemas. Defaults to false
*/
asNonEmptyTuple?: boolean;
}
2 changes: 2 additions & 0 deletions packages/plugins/typescript/enum-array/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ function buildArrayDefinition(e: GraphQLEnumType, config: EnumArrayPluginConfig)

if (config.constArrays) {
return `export const ${upperName} = [${values}] as const;`;
} else if (config.asNonEmptyTuple) {
return `export const ${upperName}: [${enumName}, ...${enumName}[]] = [${values}];`;
} else {
return `export const ${upperName}: ${enumName}[] = [${values}];`;
}
Expand Down
43 changes: 43 additions & 0 deletions packages/plugins/typescript/enum-array/tests/enum-array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,47 @@ describe('TypeScript', () => {
`);
});
});

describe('with asNonEmptyTuple', () => {
it('Should declare the array as a non-empty tuple', async () => {
const schema = buildSchema(/* GraphQL */ `
"custom enum"
enum MyEnum {
"this is a"
A
"this is b"
B
}
`);
const result = (await plugin(schema, [], {
asNonEmptyTuple: true,
})) as Types.ComplexPluginOutput;

expect(result.prepend).toBeSimilarStringTo(``);
expect(result.content).toBeSimilarStringTo(`
export const MY_ENUM: [MyEnum, ...MyEnum[]] = ['A', 'B'];
`);
});

it('Should be ignored when constArrays is true', async () => {
const schema = buildSchema(/* GraphQL */ `
"custom enum"
enum MyEnum {
"this is a"
A
"this is b"
B
}
`);
const result = (await plugin(schema, [], {
asNonEmptyTuple: true,
constArrays: true,
})) as Types.ComplexPluginOutput;

expect(result.prepend).toBeSimilarStringTo(``);
expect(result.content).toBeSimilarStringTo(`
export const MY_ENUM = ['A', 'B'] as const;
`);
});
});
});