我有两个对象:
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"
如何使用打字稿来实现这一目标?
答案 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;