使用未定义的值在Typescript中进行解构

时间:2018-06-05 20:40:48

标签: typescript destructuring

我有两个对象:

const a = {
    foo: "foo",
    bar: "bar",
}

const b = {
    foo: "fooooo",
}

我想在具有默认未定义值的方法中使用destructuring,如下所示:

const c = a or b; // I don't know which one 

然后我想做:

const { foo, bar } = c;

我想要那个

  • foo = "fooooo"bar = undefined
  • foo = "foo"bar = "bar"

如何使用打字稿来实现这一目标?

1 个答案:

答案 0 :(得分:3)

TypeScript不够智能,不能扣除{foo: string, bar: string} | {foo: string}可以写为{foo: string, bar?: string},因此您需要自行输入c,如下所示:

const c: { foo: string, bar?: string } = Math.random() > .5 ? a : b; // doesn't matter which
const { foo, bar } = c;