function compare(a: string, b: string): -1 | 0 | 1 {
return a === b ? 0 : a > b ? 1 : -1;
}
First, analyze the declared return type -1 | 0 | 1
:
This is a union of Literal types [see docs for reference]. This indicates that the return type of this function will be either:
- the number
-1
,
- the number
0
,
- or the number
1
.
Now analyze the return
statement in the function return a === b ? 0 : (a > b ? 1 : -1);
:
This is a 'nested' JavaScript Ternary Operator [see docs for reference].
The expression before the ?
is evaluated first; If it is evaluated to true
then the expression before the :
is evaluated, if false
then the expression after the :
is evaluated.
It is equivalent to the follow if
statement:
if (a === b) {
return 0;
} else {
if (a > b) {
return 1;
} else {
return -1;
{
}
or put more simply:
if (a === b) {
return 0;
} else if (a > b) {
return 1;
} else {
return -1;
{