Apollo GraphQL中TypeScript自定义Date标量类型错误求助
解决Apollo GraphQL Date自定义标量的TypeScript类型错误
你按照Apollo官方示例实现Date自定义标量时遇到的TypeScript类型错误,核心原因是未显式指定GraphQLScalarType的泛型参数,导致类型推断异常。
原代码及错误信息
原实现代码:
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; }, });
触发的类型错误:
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>>'
解决方案
显式给GraphQLScalarType指定两个泛型参数:
- 第一个参数:服务器内部处理的类型(此处为
Date) - 第二个参数:序列化后对外暴露的类型(此处为
number)
修正后的代码:
import { GraphQLScalarType, Kind } from 'graphql'; // 显式指定泛型:<内部处理类型, 对外暴露类型> export const dateScalar = new GraphQLScalarType<Date, number>({ name: 'Date', description: 'Date custom scalar type', serialize(value: Date) { return value.getTime(); // 将Date转为时间戳(number)返回给客户端 }, parseValue(value: number) { return new Date(value); // 将客户端传入的时间戳转为Date }, parseLiteral(ast) { if (ast.kind === Kind.INT) { return new Date(parseInt(ast.value, 10)); } return null; }, });
补充说明
TypeScript对GraphQLScalarTypeConfig的类型约束要求:
serialize函数接收内部处理类型(Date),返回对外暴露类型(number)parseValue和parseLiteral接收对外暴露类型(number/字符串形式数字),返回内部处理类型(Date)
显式指定泛型后,TypeScript能正确匹配各函数的参数与返回值类型,消除类型错误。
内容的提问来源于stack exchange,提问作者Anatoly
相关产品推荐
相关产品推荐

