question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Strict typing with TS

See original GitHub issue

This issue is to track a set of goals for type safety in TypeScript. In experiments, I have confirmed that all of these should be possible. While the increased verboseness has some ergonomic cost, the resulting type safety is overwhelmingly worth it in my opinion.

Object Types

For every field of a GraphQLObjectType, the resolver (including a “default resolver”) must return a value compatible with the “source” of the field’s GraphQL “type”. For example, if ChildType expects { foo: string }, then the result of ParentType’s child field cannot be { foo: 123 } or "foo".

Arguments & Input Types

The configuration of all defined arguments and input types must be checked against the types used in a resolver. For example, a resolver expecting args.foo to be a non-null string cannot be used in a field that defines argument foo as optional.

Scalars

The memory type of both custom and built-in scalars must be tracked. For example, a field with an argument configuration describing foo as a GraphQLString cannot have a resolver that expects foo to be a boolean.


Using generics and conditional types, I have been able to demonstrate that each of these is possible. However, as these effect the type signature of all primitive GraphQL components, there are a substantial number of changes across the repo. At one point I had opened a PR to DefinitelyTyped that gave partial support for strict typing of arguments, but the change was breaking (from the perspective of types) and I was too busy to effectively convey the significance before the PR was auto-closed.

As this is a natural time to implement this kind of change (during an existing push to re-type the whole codebase), I’m going to open a PR that converts the entire repo to TS in a way that accomplishes these goals. I’ll begin my changes as soon as #2139 gets merged and there’s a feature lock for 15.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:22
  • Comments:16 (7 by maintainers)

github_iconTop GitHub Comments

13reactions
mike-marcaccicommented, Oct 16, 2019

As a tiny demonstration of one piece of this, consider this partial TS reimplementation of the graphql-js codebase:

// This is a reimplementation of GraphQLScalarType with generics.
class GraphQLScalarType<TInternal, TExternal> {
  internal: TInternal;
  external: TExternal;
}

// Here are two of our built-in scalars.
const GraphQLString = new GraphQLScalarType<string, string>();
const GraphQLInt = new GraphQLScalarType<number, number>();

// We want to extract the type, using the configuration object in the `type`
// field as our source of truth. If it's set to `GraphQLString`, then we want to
// make sure that the resolver in fact returns a string.
//
// In the real-world, there are many more factors (complex types, nullable
// types, lists, default resolvers, async resolvers, etc) but this is just a
// minimal example.
type FieldConfig<TConfig> = TConfig extends GraphQLScalarType<
  infer TInternal,
  any
>
  ? {
      type: TConfig;
      resolver: () => TInternal;
    }
  : never;

// Our dummy reimplementation of `GraphQLObjectType` can infer the field types
// from the config object, so we don't actually have to pass in this generic
// parameter.
class GraphQLObjectType<
  T extends {
    [K in keyof T]: T[K] extends { type: infer V } ? FieldConfig<V> : never;
  }
> {
  constructor(config: { name: string; fields: T }) {
    // Setup happens here...
  }
}

Using this, it’s perfectly legal to create the following Person type:

const Person = new GraphQLObjectType({
  name: "Person",
  fields: {
    name: { type: GraphQLString, resolver: () => "hello" },
    age: {
      type: GraphQLInt,
      resolver: () => 12345
    }
  }
});

However, if we change the age resolver to return a string, our TypeScript will report an error, and prevent us from ever shipping bad code!

image

3reactions
mike-marcaccicommented, Mar 10, 2021

Is this the right issue to follow for TypeScript type safety? I’m surprised by the usage of any in the resolver functions.

Definitely 😄

There is active work to migrate the codebase itself to be TypeScript, and from my point of view, this could be the first step for better TS.

This is my take too. I began implementing the strong types I proposed above in a refactor to TS… but the number of changes were truly overwhelming, and impossible for any reviewer to track. Instead, I decided to wait on this heroic undertaking to land. The goal there was to migrate the codebase while minimally changing its public TS interface. Once this is complete and merged, I plan on conducting a substantial overhaul of these types to enable the kind of functionality I described above.

Read more comments on GitHub >

github_iconTop Results From Across the Web

TypeScript strictly typed: strict mode is not enough - Medium
typescript-strictly-typed enables configurations for strictly typed TypeScript, ESLint or TSLint, and optionally Angular.
Read more >
strict - TSConfig Option - TypeScript
How to provide a type shape to JavaScript objects. Narrowing. How TypeScript infers types based on runtime behavior. Variable Declarations.
Read more >
What is TypeScript? Strongly typed JavaScript - InfoWorld
In particular, TypeScript is strongly typed — that is, variables and other data structures can be declared to be of a specific type,...
Read more >
Why Static Typing & Why is TypeScript so popular? - Section.io
If you don't know, static typing is when the compiler enforces that values use the same type. Here's an example. This is valid...
Read more >
Dynamic Static Typing In TypeScript - Smashing Magazine
This is also where JavaScript gets a lot of backlash from programmers who aren't used to dynamic programming languages.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found