You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让TypeScript编译自定义GraphQL标量类型?

解决GraphQL自定义标量的TypeScript编译错误(TS2351)

问题描述

编译时触发错误:TS2351: 此表达式不可构造。类型‘typeof import(".../graphql/node_modules/graphql/index")’没有构造签名。

原代码如下:

import GraphQLScalarType, { GraphQLInt } from 'graphql';

export const CustomScalar = new GraphQLScalarType({
    ...GraphQLInt,
    name: "CustomScalar"
})

修正方案

1. 修正GraphQLScalarType的导入方式

graphql包并未将GraphQLScalarType设为默认导出,必须通过解构语法导入:

import { GraphQLScalarType, GraphQLInt } from 'graphql';

2. 正确复用GraphQLInt的配置逻辑

GraphQLInt是已实例化的标量对象,直接扩展它会带入实例的额外属性,不符合GraphQLScalarType构造函数的参数要求。需要显式提取它的核心配置方法:

export const CustomScalar = new GraphQLScalarType({
  name: "CustomScalar",
  description: GraphQLInt.description,
  serialize: GraphQLInt.serialize,
  parseValue: GraphQLInt.parseValue,
  parseLiteral: GraphQLInt.parseLiteral,
});

修改后TypeScript可正常编译,同时保留GraphQLInt的类型处理逻辑,自定义标量能正常工作。

内容的提问来源于stack exchange,提问作者jmc42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 20:19:58