Shopify 生成的类型里 GID 只是 string 怎么约束
现象#
codegen 之后 ProductVariant.id 的类型是 string,把 gid://shopify/ProductVariant/123 传给 cartLinesAdd 时 TS 不报错,运行时却返回 userErrors 说 id 无效。
原因#
- storefront-api-client 只生成结构类型,不对 ID 做品牌化,GID 就是 string
- codegen 未配置 custom scalars,ID 与 URL 一起退化成 any 或 string
- 手拼 GID 时漏了 gid://shopify/ 前缀或写错实体名,编译器无法发现
- 不同资源的 ID 形状相同,Product.id 能被传进需要变体 ID 的字段
处理步骤#
- 从
@shopify/hydrogen/storefront-api-types导入资源类型 - 定义
type GID<T> = string & {__typename: T}做品牌化 - 写构造函数
toGid('ProductVariant', id),统一补 gid 前缀 - codegen 配置补
scalars: storefrontApiCustomScalars,避免 ID 变成 any - 在
cartLinesAdd入参标注GID<'ProductVariant'>,错传时编译失败
验收标准#
把 Product.id 误传给 merchandiseId 时 tsc 报类型错误;正确 GID 调用后 userErrors 为空数组。
本文由 风格技术 技术团队整理,适用于 Shopify 标准版与 Plus 店铺。Shopify 平台能力迭代较快,具体操作路径与字段以官方文档和店铺后台实际版本为准。