update
With TypeScript 3.7 they've implemented Optional Chaining, which is like the safe navigation operator, but then better. Also the Nullish Coalescing
has found its way to the scene.
If you are using this version, the below answer is obsolete
Maybe I've missed a couple versions, but to my knowledge, TypeScript does not have an elvis operator or a safe navigation operator. The only extra thing they have is a non-null assertion operator !.
, but this is only for the compiler, and in the compiled js the !
will be removed. Angular however, does have the safe navigation operator inside their templates, but under the hood this will resolve into a logical or ||
. The benefit here is increased readability and smaller templates.
Besides that, TypeScript does have the ?:
notation, but this is used in interfaces or method parameters to indicate that the value is optional
Which leaves us with the ternary operator vs logical or. You would use the first one if there are 3 values. The question, the answer yes result, and the answer no result to said question.
And the latter when there are 2 values. Where the first one, if resolved to truthy will be the answer, and otherwise the second one, regardless of its value.
Benefit wise, I can't really say much. I would expect them to be equally fast, with a marginal difference. Perhaps readability is increased with the ternary option, which you obviously can always use instead of the logical or ||
, but personally I like to use the ||
, because it keeps the code compact.
TLDR;
Simplified if else, available everywhere
Not available in typescript/javascript/angular and essentially the same as ||
- Safe navigation operator
?.
Only available in angular templating, used to prevent null pointers in object parameter navigation
If not left hand, then right hand. Even more simplified if else. Available in typescript/javascript/angular