I have a typescript code as follows:
constructor(c?: IContact) {
this.id = c ? c.id : null;
this.caseId = c ? c.caseId : null;
this.name = c ? c.name : '';
this.email = c ? c.email : '';
this.isPrimary = c ? c.isPrimary : false;
}
What does the 'c ?' do? And how do I ensure when the user enter the contact the c.email is not null?
The
?and:is a ternary operator. It takes on the formcondition ? valueIfTrue : valueIfFalse. So,true ? "foo" : "bar"would be"foo", whereasfalse ? "foo" : "bar"would be"bar".Note that the condition is not restricted to booleans: it can be any value, and the condition is evaluated based on the truthiness of the value. An important falsy value is
nullandundefined.So,
c ? c.email : ''means that ifcis null or undefined, then default to''for the email, otherwise usec.emailfor the email.If you want to ensure
c.emailisn't null, then you can add a check: