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
null
andundefined
.So,
c ? c.email : ''
means that ifc
is null or undefined, then default to''
for the email, otherwise usec.email
for the email.If you want to ensure
c.email
isn't null, then you can add a check: