Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of QuestionMark(?) in typescript variable?

I have seen a scenario where in inside interpolation QuestionMark'?' is used with variable name. example : current?.sample.innerSample

I am not sure what it is used for. Any help is much appreciated.

Thank you

like image 951
Apurva Pathak Avatar asked Sep 10 '18 06:09

Apurva Pathak


2 Answers

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

like image 188
Konrad Grzyb Avatar answered Nov 07 '22 05:11

Konrad Grzyb


?. 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

like image 22
Sivakumar Tadisetti Avatar answered Nov 07 '22 05:11

Sivakumar Tadisetti