gpt4 book ai didi

typescript - 无法在 Apollo GraphQL 中定义自定义标量,TypeScript 输入有一些问题

转载 作者:行者123 更新时间:2023-12-05 08:03:06 24 4
gpt4 key购买 nike

我正在尝试在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com