我有一个类型:如何禁止TypeScript“错误TS2533:对象可能是'null'或'undefined'”?
type tSelectProtected = {
handleSelector?: string,
data?: tSelectDataItem[],
wrapperEle?: HTMLElement,
inputEle?: HTMLElement,
listEle?: HTMLElement,
resultEle?: HTMLElement,
maxVisibleListItems?: number
}
我宣布一个全球性的 - 模块明智 - 变量:
var $protected : tSelectProtected = {};
我指定的功能1范围适当的值:
$protected.listEle = document.createElement('DIV');
我m函数,稍后在函数2范围内:
$protected.listEle.classList.add('visible');
我得到打字稿错误:
error TS2533: Object is possibly 'null' or 'undefined'
我知道我可以使用if ($protected.listEle) {$protected.listEle}
冷静下来编译器做明确的检查,但这似乎是最不平凡的情况非常不方便。
如何在不禁用TS编译器检查的情况下处理这种情况?
我个人使用“vanilla”JavaScript中的'null'来初始化变量或属性值。这给了我直接的答案,如果给定var或prop存在,但它“没有可用值”或“在某个执行点清除了值”。这只是惯例。这可能不是TypeScript中的最佳方法,正如我在这里可以看到的答案。谢谢你的想法。 – grasnal