更新 :
- 如果您使用符合ECMAscript 2020或更高版本的Javascript,请参阅可选链接。
Typescript在[3.7版中增加了对可选链接的支持。
// use it like this
obj?.a?.lot?.of?.properties
ECMAscript 2020或早于3.7版的Typescript之前的Javascript解决方案 :
一个快速的解决方法是将try / catch辅助函数与ES6 箭头函数一起使用:
function getSafe(fn, defaultVal) { try { return fn(); } catch (e) { return defaultVal; }}// use it like thisgetSafe(() => obj.a.lot.of.properties);// or add an optional default valuegetSafe(() => obj.a.lot.of.properties, 'nothing');工作片段:
function getSafe(fn, defaultVal) { try { return fn(); } catch (e) { return defaultVal; }}// use it like thisconsole.log(getSafe(() => obj.a.lot.of.properties));// or add an optional default valueconsole.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));


