What is the use of QuestionMark(?) in typescript variable?
You can use typescript online console to check what does it mean. For example:
var obj = {
a: {
b: {
c: null
}
}
};
var test = obj.a.b.c?.d;
console.log(test) // undefined
will be translated to:
"use strict";
var _a;
var obj = {
a: {
b: {
c: null
}
}
};
var test = (_a = obj.a.b.c) === null || _a === void 0 ? void 0 : _a.d;
console.log(test); // undefined
If you do not put ? it will result in TypeError: Cannot read property 'd' of null
as c is null and d is not defined
?.
is a safe navigation operator. It prevents object paths from undefined
or null reference
errors. For ex:
If you write {{ data.somepropertyname }}
in the template
file without defining the data
member variable in typescript
file, it will throw an error like below
Cannot get
somepropertyname
of undefined
But if you write like this {{data?.somepropertyname}}
it won't throw error
Check the example Stackblitz
Do comment and uncomment line numbers 8 & 9
, you will see the output in the console