Description
Hullo! I’m upgrading some Apollo projects to GraphQL 16 and running into slight difficulties with enums. The context is that we have utilities which create or modify AST nodes:
diff --git a/src/utilities/graphql/transform.ts b/src/utilities/graphql/transform.ts
index 2a5128d05..80db6d202 100644
--- a/src/utilities/graphql/transform.ts
+++ b/src/utilities/graphql/transform.ts
@@ -2,6 +2,7 @@ import { invariant } from '../globals';
import {
DocumentNode,
+ Kind,
SelectionNode,
SelectionSetNode,
OperationDefinitionNode,
@@ -53,9 +54,9 @@ export type RemoveVariableDefinitionConfig = RemoveNodeConfig<
>;
const TYPENAME_FIELD: FieldNode = {
- kind: 'Field',
+ kind: 'Field' as Kind.FIELD,
name: {
- kind: 'Name',
+ kind: 'Name' as Kind.NAME,
value: '__typename',
},
};
The code is semantically sound, but TypeScript requires the assertion because you must reference enums directly wherever they are required (nominal typing).
enum Foo {
a = "A",
b = "B",
}
// This is a type error because we’re not referencing the enum directly.
const foo: Foo = "A";
// This is fine
const foo1: Foo = Foo.a;
The disadvantages of this change in GraphQL 16 are:
- We have to add runtime dependencies on the files which contain the enums.
- It’s slightly tricky to support ranges of graphql-js versions.
As a specific example of an enum-based difficulty, OperationTypeNode
is an enum in GraphQL 16, but it’s not exported as a value in GraphQL 15, so there is no way to reference the enum value across 15 and 16, and you get type errors if you assign strings like "query"
or "mutation"
to the enum.
I think the above two concerns are reason enough to switch to using string unions, which are structurally typed, and don’t require direct reference. We can make this a non-breaking change by exporting a namespace instead of an enum, and shadowing the identifier on the type-level with a string union.
export type Kind = "Name" | "Document" /* ... */;
export namespace Kind {
export const NAME = 'Name';
export const DOCUMENT = 'Document';
/* ... */
}
Thanks for reading. Let me know your thoughts!