提问者:小点点

无法在ApolloGraphQL中定义自定义标量,TypeScript类型有一些问题


我正在尝试在TypeScript中实现这个示例: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;
    },
});

但是有一些TypeScript错误:

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>>'

TypeScript中的新功能,无法理解我在哪里(如何)定义(扩展)这些类型?


共1个答案

匿名用户

添加了一条评论,但也找到了解决方案。

我在tsconfig. json中打开严格类型检查后遇到了这个错误(设置compilerOptions.严格=true)。您可以禁用严格类型检查或继续阅读使用严格类型检查的解决方案。

序列化的声明实际上是:

serialize: GraphQLScalarSerializer<TExternal>

GraphQLScalarSerializer的类型是:

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

这意味着您的序列化函数没有遵循定义。它应该是:

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

对于未来的读者,上面的类型在npm包中声明graphql@16.6.0