In the previous article, I created an object whose properties will get summed up within the below function and the outcome will get returned and printed out on the console.
function adding(obj : any) : number {
return obj.number1 + obj.number2
}
What will happen if I have entered an undefined object into that function instead of the object itself as follows?:-
console.log(adding(undefined))
Well, this is what you will get:-
TypeError: Cannot read properties of undefined (reading 'number1')
at adding (E:\visual_studio_code\typescript\example6.js:6:16)
at Object.<anonymous> (E:\visual_studio_code\typescript\example6.js:8:13)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
It seems like the program has generated an error message…
In order to fix this, TypeScript has introduced a feature named optional chaining or the ?. syntax into the ECMAScript standard which has been adapted by Javascript since the ES2020 version of Javascript.
Now let us modify the previous function a little bit as follows:-
function adding(obj : any) : number {
return obj?.number1 + obj?.number2
}
Call the above function again with the undefined object and you will get the following outcome:-
NaN
It seems that there is no error this time but still you still can improve on the function above.
function adding(obj : any) : number {
if(obj?.number1 && obj?.number2) {
return obj.number1 + obj.number2
} else {
return 0
}
}
The lines above simply mean if the object is undefined then 0 will get returned or else the sum of the object properties will get returned.
The revised program is as follows:-
let numberObj : any = {
number1 : 1,
number2 : 2
}
function adding(obj : any) : number {
if(obj?.number1 && obj?.number2) {
return obj.number1 + obj.number2
} else {
return 0
}
}
console.log(adding(undefined)) /* 0 */
console.log(adding(numberObj)) /* 3 */
You can sleep soundly after the above amendment to your original TypeScript program.