GraphQL 类型在由 Relay 编译时在 Typescript 中被定义为未知
Posted
技术标签:
【中文标题】GraphQL 类型在由 Relay 编译时在 Typescript 中被定义为未知【英文标题】:GraphQL types being defined as unknown in Typescript when compiled by Relay 【发布时间】:2021-07-05 06:49:19 【问题描述】:我是使用 Typescript 的新手,发现从 GraphQL 架构处理类型的方式与通过 Relay 生成的类型不匹配。
这是一个例子:
# in schema.graphql
"""
columns and relationships of "businesses"
"""
type businesses implements Node
businessId: bigint!
name: String!
// in __generated__/Business_business.graphql
export type Business_business =
readonly name: string;
readonly businessId: unknown;
readonly " $refType": "Business_business";
;
export type Business_business$data = Business_business;
export type Business_business$key =
readonly " $data"?: Business_business$data;
readonly " $fragmentRefs": FragmentRefs<"Business_business">;
;
const BusinessFragment = graphql`
fragment Business_business on businesses
name
businessId
`
type Props =
fragmentRef: Business_business$key
const Business = ( fragmentRef : Props) =>
const business = useFragment(BusinessFragment, fragmentRef)
return (
<div>
<p>my html!</>
/* I get the error: Type 'unknown' is not assignable to type 'number' for businessId */
<ChildComponent businessId=business.businessId />
</div>
)
interface Props
businessId: number
const ChildComponent = ( businessId : Props) =>
return (
<p>my business id: businessId</p>
)
为了让 Relay 了解 Hasura 类型,我需要做额外的配置吗?我通过relay docs 遵循了这个例子。
我假设 Relay 没有将 bigint
编译为 number
。
更新
我已将 Hasura 中的列类型从 bigint
更改为 Int
,这解决了问题。有没有办法告诉 Relay 如何匹配它不熟悉的类型?在这种情况下,将 bigint
转换为 number
完全没问题。
【问题讨论】:
【参考方案1】:回答您的更新:
您可以在您的relay.config.js
中添加customScalars
。我也在使用 Hasura,这是我设置的:
module.exports =
// ... your other configs
customScalars:
uuid: 'string',
int8: 'string',
bigint: 'string',
numeric: 'number',
varbit: 'string',
bit: 'string',
char: 'string',
varchar: 'string',
bool: 'boolean',
int: 'number',
int4: 'number',
float8: 'number',
timestamptz: 'string',
timetz: 'string',
jsonb: 'Record<string, unknown>',
_text: 'string',
date: 'string',
;
【讨论】:
【参考方案2】:您是否从// in __generated__/Business_business.graphql
导入类型?
有错别字吗??类型名后面的 $key 是什么?
type Props =
fragmentRef: Business_business$key
【讨论】:
我已更新问题以使此导入更加清晰。以上是关于GraphQL 类型在由 Relay 编译时在 Typescript 中被定义为未知的主要内容,如果未能解决你的问题,请参考以下文章
如何在 GraphQL (Relay) 中查询和改变数组类型?
GraphQL/Relay Schema 无法在“CreateLinkPayload”类型上查询字段“store”
中继编译器无法在 Typescript 中提取和使用 graphql 查询