我正在尝试在 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,无法理解我在哪里(如何)定义(扩展)这些类型?
最佳答案
添加了评论但也找到了解决方案。
我在 tsconfig.json(设置 compilerOptions.strict = true)中打开严格类型检查后遇到了这个错误。您可以禁用严格类型检查或继续阅读使用严格类型检查的解决方案。
serialize
的声明实际上是:
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
}
对于 future 的读者,上面的类型在 npm 包 graphql@16.6.0 中声明
关于typescript - 无法在 Apollo GraphQL 中定义自定义标量,TypeScript 输入有一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74481995/
相关文章:
macos - 在 Mac m2 Monterey 上安装 home-brew 时出现问题
javascript - 升级到 React 18 后检测到额外的点击。为什么?
blockchain - 在 remix Ide 中,这个通知是什么意思? "You have no
typescript - 如何在保持默认行为的同时扩展 tsconfig 中的类型
javascript - 是的,当 .required() 为 false 时,会继续在同一个属性上
python - ModuleNotFoundError 即使模块被识别