gpt4 book ai didi

typescript - GraphQL 查询结果中的类型不存在属性

转载 作者:行者123 更新时间:2023-12-05 06:01:22 34 4
gpt4 key购买 nike

在 React 组件中,我使用 GraphQL 查询来获取数据:

const { data, error, loading } = useGetEmployeeQuery({
variables: { id: "a34c0d11-f51d-4a9b-ac7fd-bfb7cbffa" }
});

关于数据解构

const { first_name } = data?.Employees_employees_by_pk;

类型检查返回错误

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

关于typescript - GraphQL 查询结果中的类型不存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67240260/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com