【发布时间】:2019-04-04 19:39:47
【问题描述】:
我正在使用 GraphQL,此时在我的代码中,我有一个 GraphQLError 对象,它有一个名为 extensions 的属性,其类型为 void | { [key: string]: any; }。这使得如果我尝试访问 extensions 的任何属性,我会收到此错误:
x.extensions.code === 'UNAUTHENTICATED'
Property 'code' does not exist on type 'void | { [key: string]: any; }'.
Property 'code' does not exist on type 'void'.
访问联合类型中两种类型都不存在的属性的建议解决方案如下:https://github.com/Microsoft/TypeScript/issues/12815#issuecomment-266193707
let pet = getSmallPet();
if ((<Fish>pet).swim) {
(<Fish>pet).swim();
}
else {
(<Bird>pet).fly();
}
但是,我不能在没有类型名称的情况下进行类型断言。
关于如何解决此问题的任何想法?
问候, 理查德
【问题讨论】:
-
为什么不直接使用type guards,比如
if (x.extensions) { x.extensions.code === 'UNAUTHENTICATED' }或if (!x.extensions) throw new Error('darn'); x.extensions.code === 'UNAUTHENTICATED'? -
另外,类型不需要名称。你可以写
if ((<{ [key: string]: any; }>x.extensions).code) {
标签: typescript graphql apollo