如何让打字稿确定非安全的解构场景?

问题描述

下面的示例代码会导致解构错误,因为它会尝试解构 undefined。对于这种不安全的解构代码,我们如何防止打字稿编译成功?

interface IOptionalObjectProperties {
  prop?: {
    nested?: {
      val?: string;
    };
  };
}

const object: IOptionalObjectProperties = {};
const {
  prop: {
    nested: { val }
  }
} = object;
console.log(val);

导致像

这样的运行时错误
/test.ts:24
} = object;
    ^
TypeError: Cannot read property 'nested' of undefined
    at Object.<anonymous> (/test.ts:24:5)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Module.m._compile (/node_modules/ts-node/src/index.ts:1043:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Object.require.extensions.<computed> [as .ts] (/node_modules/ts-node/src/index.ts:1046:12)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at main (/node_modules/ts-node/src/bin.ts:225:14)
    at Object.<anonymous> (/node_modules/ts-node/src/bin.ts:512:3)

编辑

答案 在配置中使用 strictnullchecks 作为 true 检测这些场景。

解决方法

使用 strictNullChecks 选项可以标记这样的场景。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...