Having trouble defining a custom scalar in Apollo GraphQL due to TypeScript typing issues

I'm attempting to apply this TypeScript example: https://www.apollographql.com/docs/apollo-server/schema/custom-scalars#example-the-date-scalar

import { GraphQLScalarType, Kind } from 'graphql';

export const dateScalar = new GraphQLScalarType({
    name: 'Date',
    description: 'Date custom scalar type',
    serialize(value: Date) {
        return value.getTime(); // Convert outgoing Date to integer for JSON
    },
    parseValue(value: number) {
        return new Date(value); // Convert incoming integer to Date
    },
    parseLiteral(ast) {
        if (ast.kind === Kind.INT) {
            // Convert hard-coded AST string to integer and then to Date
            return new Date(parseInt(ast.value, 10));
        }
        // Invalid hard-coded value (not an integer)
        return null;
    },
});

However, I am encountering TypeScript errors:

src/graphql-scalars/date-scalar.ts:6:5 - error TS2322: Type '(value: Date) => number' is not assignable to type 'GraphQLScalarSerializer<number>'.
  Types of parameters 'value' and 'outputValue' are incompatible.
    Type '{}' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 37 more.

6     serialize(value: Date) {
      ~~~~~~~~~

  node_modules/graphql/type/definition.d.ts:363:3
    363   serialize?: GraphQLScalarSerializer<TExternal>;
          ~~~~~~~~~
    The expected type comes from property 'serialize' which is declared here on type 'Readonly<GraphQLScalarTypeConfig<Date, number>>'

Being new to TypeScript, I am unsure how or where to define or extend these types. Can anyone provide guidance?

Answer №1

Just posted a comment but managed to find the solution as well.

Encountered this error after enabling strict type checking in tsconfig.json (by setting compilerOptions.strict = true). You have two options: disable strict type checking or continue reading for the solution with strict type checking enabled.

The declaration for serialize should look like this:

serialize: GraphQLScalarSerializer<TExternal>

The type of GraphQLScalarSerializer is defined as follows:

declare type GraphQLScalarSerializer<TExternal> = (
  outputValue: unknown
) => TExternal;

This means that your serialize function needs to adhere to this definition. It should be:

serialize(value: unknown) {
    return (value as Date).getTime(); // Convert outgoing Date to integer for JSON
}

For those reading this in the future, the types mentioned above are declared in the npm package [email protected]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can TypeScript support promise chaining in a functional way?

It appears that in the realm of JavaScript, one has the capability to execute: function extendPromise(promise) { return promise.then(new Promise(() => {})); } However, when incorporating types into the mix, such as function extendTypeScriptPromis ...

React with TypeScript presents an unusual "Unexpected token parsing error"

Recently, I encountered an issue with my helper function that was originally written in JavaScript and was functioning perfectly. However, as soon as I introduced TypeScript into the mix, strange behaviors started to surface. Here is the snippet of code fr ...

Executing additional code after all tests have finished in Mocha.js

In the world of MochaJS testing, it is customary to have before and after blocks for setup and teardown operations. But what if we want to execute an extra cleanup step after all test files have been processed? This is crucial to ensure that any lingering ...

When implementing useReducer with TypeScript, the error "Argument of type '(type, action) => { state: (...}' is not assignable to parameter of type 'ReducerWithoutAction<any>'" may occur

Recently, I decided to delve into learning TypeScript by building a simple shopping cart application. If you want to check out the code, feel free to visit my GitHub repository: https://github.com/CsarGomez/shopping-cart-reducers-tx I've encountered ...

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

javascript resolve order awaited

Is it safe to assume that the async function will release the execution in the order it was initiated? For instance, consider this code snippet: class Bar { public barPromise = new Promise(resolve => setTimeout(resolve, 1000)); public data = n ...

Uncover the value type of a key in TypeScript without using a discriminated union

I want to implement a type map that ensures the type of an object's value for a specific key is determined by the value of another key. For example: type CurrencyValue = { code: string; value: number; }; type FieldMap = { text: string; curren ...

Developing a continuous running test loop

Currently, I have a code that runs fine, but I am looking to modify it to run in a loop that counts the number of elements with the class="socal" and tests each link. module.exports = { 'Unitel Fitness - click' : function (browser) { bro ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...

Calling a typed function with conditional types in Typescript from within another function

In my attempt to create a conditional-type function, I stumbled upon this question on Stack Overflow. Unfortunately, it seems that the approach doesn't work well with default values (regardless of where the default value is placed). Following the advi ...

Encountering an error when trying to access this.$store.state in a basic Vuex

Encountered an error with return this.$store.state.counter: The property '$store' does not exist on the type 'CreateComponentPublicInstance<{}, {}, {}, { counter(): any; }, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, ...

Tips for organizing an array with mixed data types using JavaScript

I'm still learning JavaScript, and I'm struggling with sorting an array. Let's say I have two arrays like this: var mergedArray = result.Entities.concat(result.NonClickablePaths); var allPaths = result.AllPaths; The data in both arrays look ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Typescript: The property 'userId' is not found within the 'unknown' type

For my rxJS practice in Typescript, I wrote the following simple code. import fetch from 'node-fetch'; import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver } from &apo ...

Produce every conceivable Boolean values within TypeScript data type

I am looking to create all possible configurations based on a given type. type MagicGenerator<'withWishlist' | 'withAddToCart', PickerProps> = ?? Thus, the expected output of MagicGenerator should look like this: type ExpectedRes ...

Disallow the use of properties in a nested interface

Is there a way to define an interface or type that restricts a specific key in a child of the interface when used in union types? I am looking for the correct definition for Abc: type Abc = { someField: { prohibited?: never, }, }; type Use ...

Exploring the Implementation of Data Transfer Objects (DTO) in the Services File of a Nest

I am trying to retrieve data of a specific person from mongodb based on their username and password values, but instead of getting the data of that particular person, I am getting all the data from the database. Below is the code for the DTO: import {IsS ...

What is the method for incorporating a variable into a fragment when combining schemas using Apollo GraphQL?

In my current project, I am working on integrating multiple remote schemas within a gateway service and expanding types from these schemas. To accomplish this, I am utilizing the `mergeSchemas` function from `graphql-tools`. This allows me to specify neces ...

Using Node.js and TypeScript to define custom data types has become a common practice among developers

I offer a variety of services, all yielding the same outcome: type result = { success: boolean data?: any } const serviceA = async (): Promise<result> => { ... } const serviceB = async (): Promise<result> => { ... } However, th ...

Working with Angular2: Linking dropdown values with any number of items

Is there a way to dynamically bind drop down values with numbers from 1 to 100 using a loop in Angular2? I am currently using Ngprime dropdown for a limited number of values, but how can I achieve this for any number of values? Here is the template: < ...