0

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

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)

编辑

回答在配置中 使用strictNullChecksastrue来检测这些场景。

4

1 回答 1

0

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

于 2020-12-22T05:50:04.207 回答