【问题标题】:Access property of union type with void and unnamed type具有 void 和未命名类型的联合类型的访问属性
【发布时间】: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 ((&lt;{ [key: string]: any; }&gt;x.extensions).code) {

标签: typescript graphql apollo


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多