联合类型无法允许属性查找的原因

时间:2018-06-25 03:57:49

标签: typescript typescript2.0 tsc

这使我迷惑了很长时间:

enter image description here

基本上情况是:

interface NLUAddOpts{}
interface NLURunOpts{
  treeify: boolean
}

const fn = function(opts: NLUAddOpts | NLURunOpts){
  if(opts.treeify){  // compilation error

  }
}

为什么!如果您只是在读取一个属性,而不是该属性的子属性,那它不应该编译吗?如果在if-check中,至少应该编译。

另一方面,如果这是一项任务:

const treeify = opts.treeify;

我想我明白为什么它不能编译。

解决这个问题的最好方法是什么?

1 个答案:

答案 0 :(得分:3)

答案很简单,您已经说明opts的类型为NLUAddOptsNLURunOpts。这意味着您只能访问两种类型共有的属性,否则TS无法知道该属性是否确实存在。

现在,如果NLURunOpts总是 具有属性treeify,而NLUAddOpts将会不再具有属性,那么您可以以下:

if ('treeify' in opts) {
    // opts is now of 'NLURunOpts' type
}

您还可以定义类型保护:

function isRunOpts(opts: any): opts is NLURunOpts {
    return opts.treeify !== undefined;
}

if (isRunOpts(opts)) {
    // opts is now of 'NLURunOpts' type
}

否则,您可以执行以下操作:

if((opts as NLURunOpts).treeify) {

}

声称opts的类型为NLURunOpts