When working with TypeScript, it's important to prevent unsafe destructuring code that can lead to runtime errors. In the example below, trying to destructure undefined
can cause a destructuring error. How can we ensure TypeScript does not compile successfully for this type of unsafe destructuring?
interface IOptionalObjectProperties {
prop?: {
nested?: {
val?: string;
};
};
}
const object: IOptionalObjectProperties = {};
const {
prop: {
nested: { val }
}
} = object;
console.log(val);
This code can result in runtime errors such as:
/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
To detect and prevent such scenarios in TypeScript, using strictNullChecks
set to true
in the configuration is recommended.