Ternary Conditional Operator In TypeScript

In this article, I will explain the ternary operator and how to use it in TypeScript with an example.

Introduction

 
The ternary conditional operator(?) is not a statement but it creates conditional logic. It is used to assign a certain value to a variable based on a condition.
 
It will return the value on the left of the colon ( : ) if the expression is true, and return the value on the right of the colon if the expression is false.
 
TypeScript ternary operators take three operands.
 
Syntax
 
condition ? result1 : result2;
 
The following example shows how to use a ternary condition operator in TypeScript.
 
Step 1
 
Open Visual Studio 2012 and click "File" -> "New" -> "Project...". A window is opened. In this window, click HTML Application for TypeScript under Visual C#.
 
Provide the name of your application as "Ternary_Operator" and then click "Ok".
 
Step 2
 
After this session the project has been created; a new window is opened on the right side. This window is called the Solution Explorer. The Solution Explorer contains the ts file, js file, and CSS files.
 
Coding
 
ternary_operator.ts
  1. class ternary_operator {  
  2.  condition() {  
  3.   var first = 5;  
  4.   var second = 3;  
  5.   var result = (first > second) ? "That is true : 5>3" : "That is false : 5<3";  
  6.   alert(result);  
  7.  }  
  8. }  
  9. window.onload = () => {  
  10.  var obj = new ternary_operator();  
  11.  obj.condition();  
  12. };   
ternaryoperatot_Demo.htm
  1. <!DOCTYPEhtml>  
  2. <html lang="en"  
  3.     xmlns="http://www.w3.org/1999/xhtml">  
  4.     <head>  
  5.         <meta charset="utf-8"/>  
  6.         <title>Ternary operator</title>  
  7.         <link rel="stylesheet" href="app.css"type="text/css"/>  
  8.         <script src="app.js"></script>  
  9.     </head>  
  10.     <body>  
  11.         <h2>Ternary Condition Operator in TypeScript</h2>  
  12.         <div id="content"/>  
  13.     </body>  
  14. </html>    
app.js
  1. var ternary_operator = (function() {  
  2.  function ternary_operator() {}  
  3.  ternary_operator.prototype.condition = function() {  
  4.   var first = 5;  
  5.   var second = 3;  
  6.   var result = (first > second) ? "That is true : 5>3" : "That is false : 5<3";  
  7.   alert(result);  
  8.  };  
  9.  return ternary_operator;  
  10. })();  
  11. window.onload = function() {  
  12.  var obj = new ternary_operator();  
  13.  obj.condition();  
  14. };  
Output
 
ternary conditional operator
 
Referenced By