Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

The inline ternary operator (?)

The inline ternary operator is just an alternative way of declaring a double-selection structure:

let isValid: boolean = true; 
let message = isValid ? "Is valid!" : "Is NOT valid!"; 
console.log(message); 

The preceding code snippet declares a variable of type boolean and name isValid. Then, it checks whether the variable or expression on the left-hand side of the operator ? is equal to true.

If the statement turns out to be true, the expression on the left-hand side of the character will be executed and the message Is valid! will be assigned to the message variable.

On the other hand, if the statement turns out to be false, the expression on the right-hand side of the operator will be executed and the message, Is NOT valid! will be assigned to the message variable.

Finally, the value of the message variable is displayed on the screen.