Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is optional chaining (Elvis operator) in TypeScript and how does it work? [duplicate]

Tags:

typescript

I'm trying to understand what is optional chaining (Elvis operator) and how it works, and what it is used for in TypeScript?

public static getName(user: IUser){
    if(user.firstName != null && user.firstName != ""){
        return user.firstName;
    }

    if(user.lastName != null && user.lastName != ""){
        return user.lastName;
    }

    return user.username;
}

Could I, for example, apply optional chaining to the code above to make it shorter?

-Edit-

Updated the question with code, after comment.

export interface IUser {
    id: string;
    firstName: string;
    lastName: string;
    username: string;
}
like image 370
O S Avatar asked Jun 05 '20 12:06

O S


1 Answers

Optional Chaining operator

The optional chaining operator helps you write expressions that stops running as soon as null or undefined is encountered.

For example you can refactor your code like this if you want to check that user is not null or undefined:

public static getName(user: IUser): string {
    if(user?.firstName != null && user?.firstName != ""){
        return user.firstName;
    }

    if(user?.lastName != null && user?.lastName != ""){
        return user.lastName;
    }

    return user?.username || "";
}

What is really interesting is that you can use it with arrays and functions:

// Access first element of array if array is set
const element = array?.[0];

// Call function if set
myFunction.(args);

But in your case, the nullish coalescing operator is more suitable to shroten the code.

Nullish Coalescing operator

The nullish coalescing operator acts like the logical operator || excepts that it fallbacks to the default value if the value checked equals null or undefined only. It prevents the bugs created with || when the value equals 0 or Nan because || only checks for nullish expression.

Here is what your code would look like:

public static getName(user: IUser){
    return user?.firstName ?? user?.lastName ?? user?.username ?? "";
}

Above both operators are used for a more robust code.

More on the bugs the logical operator || can induce

Check this example: you create an app where a user can set a timer. The user can choose a time greater than 0, but if he doesn't, you set a default time for them. This is how you get the time for the timer:

const time = userTime || defaultTime;

If the user enters a number strictly greater than 0, it works as you expect and time === userTime. But if they enter 0, the logical operator || detects 0 as a nullish expression and fallbacks to defaultTime.

To avoid this, use the nullish coalescing operator that only fallbacks if userTime equals null or undefined:

const time = userTime ?? defaultTime;

The code above will work as expected.

like image 183
Baboo Avatar answered Sep 28 '22 15:09

Baboo