简体   繁体   English

Typescript:使用解构缩小类型

[英]Typescript: narrowing types with destructuring

The following code errors:以下代码错误:

type Foo = {
  a: true,
  b: null,
  c: null
} | {
  a: false,
  b: Error,
  c: null
} | {
  a: false,
  b: null,
  c: { prop: number}
}

function getFoo(): Foo {

  return { a: false, b: null, c: { prop: 5 } };

}

const { a, b, c } = getFoo();

if (!a && !b) {
  console.log(c.prop)
}

The error given is:给出的错误是:

Object is possibly 'null'.(2531)

This makes somewhat sense, because when the result from getFoo() was destructured, the types from the larger Foo object was lost.这有点道理,因为当getFoo()的结果被解构时,更大的Foo object 中的类型丢失了。

However, I'm trying to replicate what the Apollo React client is doing:但是,我正在尝试复制 Apollo React 客户端正在做的事情:

const { loading, error, data } = useQuery('...');

if (loading) {
  return '..';
}
if (error) {
  return '..';
}
return data.foo;

I'm having a hard time figuring out from their source how they make this work.我很难从他们的来源弄清楚他们是如何做到这一点的。

Is this doable in Typescript at all?这在 Typescript 中是否可行? My best guess is that their types might not be 100% accurate, and they say they always return data even when they don't.我最好的猜测是他们的类型可能不是 100% 准确的,他们说即使他们没有返回数据,他们也总是返回data

It is not possible to have type guard between 2 variables.在 2 个变量之间不可能有类型保护。 You can make a link between variable a and b to tell that: if a condition of a is met ==> b is something else.您可以在变量 a 和 b 之间建立联系来说明:如果满足 a 的条件 ==> b 是别的东西。 For Apollo React client, I think that strictNullChecks is disabled对于 Apollo React 客户端,我认为 strictNullChecks 已禁用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM