Typescript and value can't be null

660 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

The ? and : is a ternary operator. It takes on the form condition ? valueIfTrue : valueIfFalse. So, true ? "foo" : "bar" would be "foo", whereas false ? "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 and undefined.

So, c ? c.email : '' means that if c is null or undefined, then default to '' for the email, otherwise use c.email for the email.

If you want to ensure c.email isn't null, then you can add a check:

this.email = c ? c.email : '';
if (this.email === null) {
    throw new ValueError("Email cannot be null.");
}
0
On

The c ? c.A : null ensures that c is not undefined before it attempts to access its attribute. Since your input is optional ((c?: IContact)), you would need that check.

Here is the code to ensure c.email is not null -

  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;
  }

You can replace the || with a ??. Works the same.