这使我迷惑了很长时间:
基本上情况是:
interface NLUAddOpts{}
interface NLURunOpts{
treeify: boolean
}
const fn = function(opts: NLUAddOpts | NLURunOpts){
if(opts.treeify){ // compilation error
}
}
为什么!如果您只是在读取一个属性,而不是该属性的子属性,那它不应该编译吗?如果在if-check中,至少应该编译。
另一方面,如果这是一项任务:
const treeify = opts.treeify;
我想我明白为什么它不能编译。
解决这个问题的最好方法是什么?
答案 0 :(得分:3)
答案很简单,您已经说明opts
的类型为NLUAddOpts
或NLURunOpts
。这意味着您只能访问两种类型共有的属性,否则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