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

Destructuring in Typescript with undefined values

我有 2 个对象:

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

const b = {
    foo: "fooooo",
}

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

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

那我想做:

const { foo, bar } = c;

我想要那个

我如何使用 typescript 完成此操作?

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;