Learn Typescript Ternary, String, and Negation Operators

ternary operator in typescript

These are also called Conditional Operators.

This operator is applied to conditional expressions in which the expression is evaluated and returns the conditional logic.

Syntax:

 Condition? true-result? false-result;

The condition is an expression that is evaluated first. if the condition is true, true-result is evaluated if the condition is false, false-result is evaluated.

This is a shorthand syntax for simple if-else conditional expressions.

We will see the example

Even Number check using the ternary operator:

var number1 = 15;
var number2 = 16;
console.log(number1 % 2 ? "Even Number" : "Odd Number"); // returns Even Number
console.log(number2 % 2 ? "Even Number" : "Odd Number"); // returns Odd Number

String Concatenation Operator

These are also called string append operators which are operated on strings and the symbol is + (plus). Appends the strings from the right side and assigns them to the left side. It does not add any extra space as part of string concat operations

var appendTest = "Concat" + " values";
console.log(appendTest); // returns Concat values

plus operator can be applied to multiple strings and append the strings and returns the concatenated string

Negation Operator in typescript

This operator changes the sign of a number and the symbol is -(minus). If the value is positive, negation returns negative if the value is negative negation returns positive

var number1 = 8;
console.log(number1); //returns 8
console.log(-number1); // returns -8

TypeOf and InstaneOf operator

both operators are unary. These operators have only a single operand typeOf operator that returns the data type of the value.

The instaceOf operator checks if the specified object is of the generic object type or not.

These two operators are used for type checking and safety.

Please see this Complete typeOf, Instanceof examples post for more examples.
Examples

var strinTest = "test";
console.log(typeof strinTest); //returns : string