The Typescript conditional operator is a Ternary Operator, which takes three operands. The first operand is a condition
to evaluate. It is followed by a question mark (?
), then an expression (expression1
). It is then followed by a colon (:
) and second expression (expression2
). If the condition
is true, then expression1
executes & if the condition
is false, then expression2
executes. The conditional operator is a shorthand way to write an If else
statement.
The syntax is as follows
Syntax
1 2 3 4 5 | Syntax condition ? expression1 : expression2; |
Wherecondition
: is a boolean expression, which returns true false.expression1
: executes if the condition is true.expression2
: executes if the condition is false.
Example
1 2 3 4 5 6 | const isValid = true; // Conditional operator const message = isValid ? 'Valid' : 'Failed'; |
Ternary Operator is an operator which takes three operand. The conditional operator is the only one Ternary Operator in Typescript. If the operator requires two operand, then it is a binary operator. If it requires only one operator, then it is a Unary Operator
Conditional operator Example
1 2 3 4 5 6 7 8 9 | let a=10 let b=15 let c= (a > b ? 'a is greater than b' : 'a is not greater than b'); console.log(c) //a is not greater than b |
Conditional Operator is a shortcut to If condition. The above code is same as the following if statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | let a=10 let b=15 let c:string if (a > b ) { c='a is greater than b' } else { c='a is not greater than b' } console.log(c) //a is not greater than b |
Multiple Conditions in Ternary Operator
We can also add Multiple Conditions or nested conditions to a Ternary Operator.
1 2 3 4 5 6 7 8 9 10 11 | function check(a:number,b:number) { let c= (a == b ? 'a is equal to b' : (a >b) ? 'a is greater than b' : 'b is greater than a'); console.log(c) } check(10,10) //a is equal to b check(11,10) //a is greater than b check(10,11) //b is greater than a |
The check function is equivalent to the following if else if else
statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function check(a:number,b:number) { let c:string if (a == b ) { c='a is equal to b'; } else if (a > b) { c='a is greater than b' } else { c='b is greater than a' } console.log(c) } |
Reference
Read More
- Complete Typescript Tutorial
- Typescript Operators
- Arithmetic Operators
- Unary plus / Unary minus Operators
- Increment/Decrement Operators
- Comparison / Relational Operators
- Equality Operator / Strict Equality Operators
- Ternary Conditional Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Nullish coalescing operator
- Comma Operator in Typescript
- Operator Precedence