从接口解构值,否则解构未定义

时间:2018-11-16 03:01:36

标签: typescript

我正在使用TS 2.4。

我有一个函数,该函数采用IConcur,这是接口定义为:

interface IConcur = {
   value: boolean,
   type: number
}

我将其用作函数的参数:

const doit = ({ value, type }: void | IConcur = {}) => {}

但是这给了我错误:

  

[ts]   类型'{}'不能分配给类型'void | IConcurrency”。     类型“ {}”不可分配给类型“ IConcurrency”。       类型“ {}”中缺少属性“ numberValue”。 [2322]

如果参数为undefined,则希望将值破坏为undefined。我怎样才能让TS接受呢?

1 个答案:

答案 0 :(得分:1)

肮脏的方式(仅在没有严格的null检查的情况下有效):您必须明确声明IConcur成员的不确定性:

const doit = ({ value, type }: IConcur = { value: undefined, type: undefined }) => {}

一种更干净的方法是在方法主体中进行结构分解(以增加一行为代价),或者甚至更好的做法是为未定义的情况添加特定的if子句(如果在您的情况下可行): / p>

// without if
const doit = (concur?: IConcur) => {
  const { value, type } = concur || { value: undefined, type: undefined };
}

// with if
const doit = (concur?: IConcur) => {
 if (concur === undefined) {
    // special case 
  } else {
    const { value, type } = concur;
    // default case
  }  
}

在我看来,最后一种方法是最好的方法,因为对于大多数开发人员而言,它易于阅读和理解(其他方法则更容易破解)。

相关问题