0

Example code below would lead to a destructuring error because it'd try to destructure undefined. How can we prevent typescript from compiling successfully for this kind of unsafe destructuring code?

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

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

leads to runtime errors like

/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)

EDIT

ANSWER Using strictNullChecks as true in config detects these scenariosl.

Meet
  • 294
  • 3
  • 8
  • your code does not even compile correctly with strictNullChecks. – ABOS Dec 21 '20 at 16:16
  • It's not accepted in the playground: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJIHkAOZgHsRwA26ARgFYQJgAKUum0OEAzsgN4BQyymdmA-AC52XbshAtIAEyEixYgG5FZzMFFABzANyjuAXx36dejhwT5VyXOUphhGbHgLEbVWvUbAWyALzsDZhZgcjx8wpzyEqoQUuHISoTIJvocer5WrmA65iDMuIQQAHSEuBoAFAkAlDpAA – jonrsharpe Dec 21 '20 at 16:32
  • Is the answer to this question just "use `--strictNullChecks`"? I'm inclined to close this as non-reproducible without some more information from OP – jcalz Dec 21 '20 at 16:42
  • @jcalz yeah seems like that is it, strictNullChecks which seem to be enabled by default on the playground. It complies without that which led to this question. Thanks everyone! – Meet Dec 21 '20 at 19:28

1 Answers1

0

Using the strictNullChecks option can flag scenarios like this.

Meet
  • 294
  • 3
  • 8