属性 GraphQL 查询结果中的类型不存在
Property does not exist on type in GraphQL query result
在 React 组件中,我使用 GraphQL 查询来获取数据:
const { data, error, loading } = useGetEmployeeQuery({
variables: { id: "a34c0d11-f51d-4a9b-ac7fd-bfb7cbffa" }
});
关于数据解构
const { first_name } = data?.Employees_employees_by_pk;
类型检查returns一个错误
Property 'first_name' does not exist on type 'Maybe<{ __typename?: "Employees_employees" | undefined; } & Pick<Employees_Employees, "id" | "first_name" | "last_name" | "email" | "avatar" | "started_at" | "created_at" | "updated_at">> | undefined'
试图将默认值 ""
分配给 first_name
,但这无助于消除错误。
这些类型是用 graphql-codegen 生成的:
export type GetEmployeeQuery = (
{ __typename?: 'query_root' }
& { Employees_employees_by_pk?: Maybe<(
{ __typename?: 'Employees_employees' }
& Pick<Employees_Employees, 'id' | 'first_name' | 'last_name' | 'email' | 'avatar' | 'started_at' | 'created_at' | 'updated_at'>
)> }
);
如何让查询结果很好地解构?
此代码应该有效
if( data && data.Employees_employees_by_pk ) {
// no undefined here
// safe access to 'base type' fields
const { first_name } = data.Employees_employees_by_pk;
// use first_name
}
... 它在逻辑上(和类型上)不同于
const { first_name } = data?.Employees_employees_by_pk;
// possible access/destructure from undefined
在 React 组件中,我使用 GraphQL 查询来获取数据:
const { data, error, loading } = useGetEmployeeQuery({
variables: { id: "a34c0d11-f51d-4a9b-ac7fd-bfb7cbffa" }
});
关于数据解构
const { first_name } = data?.Employees_employees_by_pk;
类型检查returns一个错误
Property 'first_name' does not exist on type 'Maybe<{ __typename?: "Employees_employees" | undefined; } & Pick<Employees_Employees, "id" | "first_name" | "last_name" | "email" | "avatar" | "started_at" | "created_at" | "updated_at">> | undefined'
试图将默认值 ""
分配给 first_name
,但这无助于消除错误。
这些类型是用 graphql-codegen 生成的:
export type GetEmployeeQuery = (
{ __typename?: 'query_root' }
& { Employees_employees_by_pk?: Maybe<(
{ __typename?: 'Employees_employees' }
& Pick<Employees_Employees, 'id' | 'first_name' | 'last_name' | 'email' | 'avatar' | 'started_at' | 'created_at' | 'updated_at'>
)> }
);
如何让查询结果很好地解构?
此代码应该有效
if( data && data.Employees_employees_by_pk ) {
// no undefined here
// safe access to 'base type' fields
const { first_name } = data.Employees_employees_by_pk;
// use first_name
}
... 它在逻辑上(和类型上)不同于
const { first_name } = data?.Employees_employees_by_pk;
// possible access/destructure from undefined