具有 void 和未命名类型的联合类型的访问属性 [英] Access property of union type with void and unnamed type

查看:24
本文介绍了具有 void 和未命名类型的联合类型的访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 GraphQL,此时在我的代码中,我有一个 GraphQLError 对象,它有一个名为 extensions 的属性,它的类型为 void |{ [键:字符串]:任何;}.这使得如果我尝试访问 extensions 的任何属性,我会收到此错误:

I'm working with GraphQL and at this point in my code, I have a GraphQLError object, which has a property called extensions which has a type of void | { [key: string]: any; }. This is making it so that if I try to access any property of extensions, I get this error:

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

A proposed solution to accessing properties that don't exist on both types in a union type is here: https://github.com/Microsoft/TypeScript/issues/12815#issuecomment-266193707

let pet = getSmallPet();

if ((<Fish>pet).swim) {
    (<Fish>pet).swim();
}
else {
    (<Bird>pet).fly();
}

但是,我不能在没有类型名称的情况下进行类型断言.

However, I cannot do a type assertion without a type name.

有关如何解决此问题的任何想法?

Any ideas on how I can fix this issue?

问候,理查德

推荐答案

你可以使用类型保护来缩小联合的类型:

You can use type guards to narrow the type of the union:

declare let o: {
    extensions: void | { [key: string]: any; }
}

o.extensions["test"] // error
if (o.extensions) {
    o.extensions["test"] // ok here
}

注意 只有当您打开 strictNullChecks 时,您的代码才会抛出错误

Note Your code will throw an error only if you have strictNullChecks turned on

这篇关于具有 void 和未命名类型的联合类型的访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆