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.