Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade issues with TypeScript enums and nominal typing #3356

Closed
brainkim opened this issue Nov 2, 2021 · 10 comments
Closed

Upgrade issues with TypeScript enums and nominal typing #3356

brainkim opened this issue Nov 2, 2021 · 10 comments

Comments

@brainkim
Copy link

brainkim commented Nov 2, 2021

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:

  1. We have to add runtime dependencies on the files which contain the enums.
  2. 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!

@saihaj
Copy link
Member

saihaj commented Nov 3, 2021

Why not use the enum directly?

 const TYPENAME_FIELD: FieldNode = {
-  kind: 'Field',
+  kind: Kind.FIELD,
   name: {
-    kind: 'Name',
+    kind: Kind.NAME,
     value: '__typename',
   },
 };

Let me know your thoughts!

Exporting namespaces and string unions imo isn't very clean.

@brainkim
Copy link
Author

brainkim commented Nov 3, 2021

@saihaj

Why not use the enum directly?

I’m not sure I want to import a file from graphql-js just to access the enum value. And in the case of OperationTypeNode, the enum does not exist in v15.

Exporting namespaces and string unions imo isn't very clean.

I agree it could be a pain to deal with and write. I still think the nominal typing part about enums is tricky. Any other solution which preserves the structural typing behavior and also allows for dot notation access would be acceptable to me.

@IvanGoncharov
Copy link
Member

@brainkim Practically speaking is it a blocker for adding v16 support to apollo-client?
I will keep this issue open anyway just want to know how urgent it?

I’m not sure I want to import a file from graphql-js just to access the enum value. And in the case of OperationTypeNode, the enum does not exist in v15.

It looks like you are using visit in Apollo client:
https://github.com/apollographql/apollo-client/blob/8716cbcaaa5f633768f2e44055921caa7858fcf9/src/utilities/graphql/transform.ts#L16
If so you already bundling entire Kind, see:

for (const kind of Object.values(Kind)) {
enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind));
}

It’s slightly tricky to support ranges of graphql-js versions.

If you have any idea on how to address this happy to implement it in previous versions.

We have to add runtime dependencies on the files which contain the enums.

Const enums are ideal for this case however we can't do Object.values on them.
Ideally, TS would have a mechanism that allows us to mark enum as safe to inline but keep the runtime part for the case when you actually need it.

@benjie
Copy link
Member

benjie commented Nov 3, 2021

Could we do something like this, I wonder?

export const Kind = {
  OBJECT: 'ObjectType' as const,
  OBJECT_FIELD: 'ObjectField' as const
};
export type Kind = typeof Kind[keyof typeof Kind];

const a: Kind = Kind.OBJECT;
const b: Kind = 'ObjectType';

export interface ASTNode {
  kind: typeof Kind.OBJECT
}

https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAYwgOwM7wNIEtkBM4C8cA3gFBxwDyAQgFICiAwgCoBccA5JQEYBWwCGMwCeYYBzgBDVIhToANOSp0mzAPoAxAJL0AMgBF2XPgJgaswADa4J02WhikAvgG5SoSLDgxRwONjxCb18IADN-HFwAbQBrYGEw4LFEgNwAXTdSJAcpdlSg1IA6GgYWN2z0OG48yKDjfkERMQ5Mj2h4HBhgKFDJBD8AQQBlZgA5CFw-MgoYyPYfZPCiktVnIA

@yaacovCR
Copy link
Contributor

yaacovCR commented Nov 3, 2021

Wow, that is neat!

@brainkim
Copy link
Author

brainkim commented Nov 3, 2021

@IvanGoncharov It’s not a blocker! Thankfully with TypeScript there are workarounds. Just surfacing the struggle in case others having it.

@benjie keyof typeof is a new one to me! That’s fantastic.

You can also use the const on the object literal, and freeze the Object to prevent unwanted mutations too.

export const Kind = Object.freeze({
  OBJECT: 'ObjectType',
  OBJECT_FIELD: 'ObjectField',
} as const);
export type Kind = typeof Kind[keyof typeof Kind];

const a: Kind = Kind.OBJECT;
const b: Kind = 'ObjectType';

export interface ASTNode {
  kind: typeof Kind.OBJECT
}

@brainkim brainkim changed the title Enums and nominal typing Upgrade issues with TypeScript enums and nominal typing Nov 3, 2021
@brainkim
Copy link
Author

brainkim commented Nov 3, 2021

Another detail is that we’re using typeof Enum in various places (https://github.com/graphql/graphql-js/blob/main/src/language/directiveLocation.ts#L33), and it doesn’t actually seem to work as expected.

enum Foo {
    a = 1,
    b = 2,
}

type FooLegacy = typeof Foo;

const foo: Foo = Foo.a;

// this errors
const foo1: FooLegacy = Foo.a;

https://www.typescriptlang.org/play?ssl=11&ssc=31&pln=1&pc=1#code/KYOwrgtgBAYg9nKBvAUFdUCGUC8UCMANGhgEa5QBMxAviigC4CeADsLAgDLADmmAxkwrM2cAGYc4Abnr84IAM4MoYhAC5JFeHAB0mGSgD0hqAwAWASwVRgAJ1txbClHMXLVcfBu3c+grQh6UkA

@yaacovCR
Copy link
Contributor

Tracking in newer issue #4253

@JoviDeCroock
Copy link
Member

These are two distinct issues, let's leave this open.

@JoviDeCroock JoviDeCroock reopened this Oct 27, 2024
JoviDeCroock added a commit that referenced this issue Oct 30, 2024
This gets rid of enums for two reasons

- TypeScript does not really compile them size efficiently, see
[here](https://www.runpkg.com/[email protected]/language/kinds.mjs)
  - Raw size kinds.js before: 2800bytes
  - Raw size kinds.js after: 2200 bytes
- It's not kind to plains strings as seen in
#3356

Resolves #3356

This does not intend to fix the tree-shaking issue as seen in
#4253, for that we'd need to
fully normalize these exports and sacrifice the DX of the namespaces. I
do think that it becomes easier as plain strings will be "easier"
compared to before so if you're not doing comparisons you can opt out of
the `Kind` namespace.

<details>
  <summary>See new output</summary>

```js
/**
 * The set of allowed kind values for AST nodes.
 */
exports.Kind = {
    /** Name */
    NAME: 'Name',
    /** Document */
    DOCUMENT: 'Document',
    OPERATION_DEFINITION: 'OperationDefinition',
    VARIABLE_DEFINITION: 'VariableDefinition',
    SELECTION_SET: 'SelectionSet',
    FIELD: 'Field',
    ARGUMENT: 'Argument',
    FRAGMENT_ARGUMENT: 'FragmentArgument',
    /** Fragments */
    FRAGMENT_SPREAD: 'FragmentSpread',
    INLINE_FRAGMENT: 'InlineFragment',
    FRAGMENT_DEFINITION: 'FragmentDefinition',
    /** Values */
    VARIABLE: 'Variable',
    INT: 'IntValue',
    FLOAT: 'FloatValue',
    STRING: 'StringValue',
    BOOLEAN: 'BooleanValue',
    NULL: 'NullValue',
    ENUM: 'EnumValue',
    LIST: 'ListValue',
    OBJECT: 'ObjectValue',
    OBJECT_FIELD: 'ObjectField',
    /** Directives */
    DIRECTIVE: 'Directive',
    /** Types */
    NAMED_TYPE: 'NamedType',
    LIST_TYPE: 'ListType',
    NON_NULL_TYPE: 'NonNullType',
    /** Type System Definitions */
    SCHEMA_DEFINITION: 'SchemaDefinition',
    OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition',
    /** Type Definitions */
    SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition',
    OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition',
    FIELD_DEFINITION: 'FieldDefinition',
    INPUT_VALUE_DEFINITION: 'InputValueDefinition',
    INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition',
    UNION_TYPE_DEFINITION: 'UnionTypeDefinition',
    ENUM_TYPE_DEFINITION: 'EnumTypeDefinition',
    ENUM_VALUE_DEFINITION: 'EnumValueDefinition',
    INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition',
    /** Directive Definitions */
    DIRECTIVE_DEFINITION: 'DirectiveDefinition',
    /** Type System Extensions */
    SCHEMA_EXTENSION: 'SchemaExtension',
    /** Type Extensions */
    SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension',
    OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension',
    INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension',
    UNION_TYPE_EXTENSION: 'UnionTypeExtension',
    ENUM_TYPE_EXTENSION: 'EnumTypeExtension',
    INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension',
};
```

</details>

Currently seeing whether we should disable the redeclare lint-rule and
whether there is a better way to type our `nodeKinds`
@JoviDeCroock
Copy link
Member

This will be solved in v17 after #4254

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants