【问题标题】:Destructuring in Typescript with undefined values使用未定义值在 Typescript 中解构
【发布时间】:2018-06-06 04:50:27
【问题描述】:

我有 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;

我想要那个

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

我怎样才能用 typescript 来做到这一点?

【问题讨论】:

    标签: typescript destructuring


    【解决方案1】:

    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;
    

    【讨论】:

    • 这种方法的问题是我不希望c 拥有bar 属性。这就是为什么我希望解构返回undefined,所以c 仍然没有bar 属性。我想我必须为此创建一个包装函数。谢谢
    • 什么意思? c 可能有bar 属性,不管你想不想,如果你将c 设置为a,它就会有它......如果没有,它会得到undefined
    猜你喜欢
    • 1970-01-01
    • 2021-02-10
    • 2017-07-13
    • 1970-01-01
    • 2018-09-29
    • 2017-09-29
    • 2018-01-12
    • 2020-03-27
    • 2019-05-25
    相关资源
    最近更新 更多