我尝试使用TypeScript在GraphQL查询上添加查询类型,但我不明白为什么TS返回此错误:
Property 'userMe' does not exist on type 'Query | null'.
我的查询:
const { userMe }: Query | null = cache.readQuery({
query: ME,
});
我的类型:
export type Query = {
__typename?: 'Query';
files?: Maybe<Array<Maybe<UploadFile>>>;
me?: Maybe<UsersPermissionsMe>;
userMe?: Maybe<CustomUsersPermissionsMe>;
};
userMe
存在,但不是必需的。我不明白为什么TS会为此哭泣:D我使用TS v3.7.5。
有人可以帮助我吗?
答案 0 :(得分:0)
这是因为cache.readQuery()
的返回值可能是null
。根据错误消息的外观,其返回类型为Query | null
。如果代码为null,则会引发异常。
代替:
const { userMe }: Query | null = cache.readQuery({
query: ME,
});
您需要这样做:
const query = cache.readQuery({
query: ME,
});
const userMe = query && query.userMe ? query.userMe: undefined
您需要处理以下事实:在非空查询中,查询结果可能为空,并且userMe
可能为undefined
。
从高层次上讲,TypeScript迫使您编写代码以应对在运行时事物可能是null
或undefined
的事实。您的类型签名可以对两种情况进行建模(空查询结果和非空查询上的未定义字段)。
在代码中如何处理它取决于程序在这种情况下的行为。
至少您要做类似的事情:
if (userMe !=== undefined) {
// TS now knows that in here userMe is Maybe<CustomUsersPermissionsMe>
}
您必须防止未定义,因为未定义在Query
对象本身上可以为空。然后是Maybe
,因此您需要编写一堆警戒线。