如何在TypeGraphQL中为键值对对象指定显式类型
解决TypeGraphQL中索引签名类型的显式指定问题
TypeGraphQL的反射系统无法自动推断TypeScript的索引签名类型(如{ [key: string]: string }),因此需要手动指定对应的GraphQL标量类型,以下是两种可行方案:
方案一:使用第三方JSON标量(快速实现)
- 先安装依赖包:
npm install graphql-scalars # 或 yarn add graphql-scalars
- 修改你的
Result类代码,导入GraphQLJSON并显式指定字段类型:
import { ObjectType, Field } from "type-graphql"; import { GraphQLJSON } from "graphql-scalars"; @ObjectType() export class Result { @Field({ nullable: true }) domainName?: string; @Field(() => [String], { nullable: true }) uniqueIds?: string[]; @Field(() => GraphQLJSON, { nullable: true }) resultKeyVal: { [key: string]: string }; }
这种方式直接利用JSON标量存储任意键值对,无需额外验证,适合快速开发场景。
方案二:自定义字符串映射标量(严格类型校验)
如果需要确保键值对的值必须是字符串类型,可以自定义专门的标量:
- 创建自定义标量类:
import { ObjectType, Field, Scalar, CustomScalar } from "type-graphql"; import { GraphQLScalarType, Kind } from "graphql"; @Scalar("StringToStringMap", () => Object) export class StringToStringMapScalar implements CustomScalar<string, { [key: string]: string }> { description = "仅允许字符串键对应字符串值的映射类型"; parseValue(value: unknown): { [key: string]: string } { if (typeof value !== "object" || value === null) { throw new Error("StringToStringMap 必须是对象类型"); } for (const key in value) { if (typeof value[key] !== "string") { throw new Error(`键 "${key}" 对应的值必须是字符串`); } } return value as { [key: string]: string }; } serialize(value: { [key: string]: string }) { return value; } parseLiteral(ast): { [key: string]: string } { if (ast.kind !== Kind.OBJECT) { throw new Error("StringToStringMap 的字面量必须是对象"); } const result: { [key: string]: string } = {}; for (const field of ast.fields) { if (field.value.kind !== Kind.STRING) { throw new Error(`键 "${field.name.value}" 对应的值必须是字符串字面量`); } result[field.name.value] = field.value.value; } return result; } }
- 在
Result类中使用这个自定义标量:
@ObjectType() export class Result { @Field({ nullable: true }) domainName?: string; @Field(() => [String], { nullable: true }) uniqueIds?: string[]; @Field(() => StringToStringMapScalar, { nullable: true }) resultKeyVal: { [key: string]: string }; }
- 生成Schema时注册该标量:
import { buildSchema } from "type-graphql"; import { StringToStringMapScalar } from "./your-scalar-path"; const schema = await buildSchema({ resolvers: [/* 你的Resolver类 */], scalarsMap: [{ type: StringToStringMapScalar, scalar: StringToStringMapScalar }], });
这种方式会在解析和序列化时严格校验类型,避免非法值传入。
内容的提问来源于stack exchange,提问作者Sujit Chavan
相关产品推荐
相关产品推荐

