Learn Typescript Ternary, String, and Negation Operators

Ternary Operator in TypeScript

The ternary operator, also known as a conditional operator, is applied to conditional expressions, where the expression is evaluated and returns the conditional logic.

Syntax:

 Condition? true-result? false-result;

The condition is an expression 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.

Let’s see an example.

Even Number check using the ternary operator:

const number1 = 15;
const 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(+)

The string concatenation operator, represented by + (plus), is used to append strings together. It operates on strings and 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

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

The plus operator can be applied to multiple strings to concatenate them and returns the concatenated string.

Negation Operator in TypeScript

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

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

typeof and instanceof Operators

Both operators are unary. The typeof operator returns the data type of the value, while the instanceof operator checks if the specified object is of the generic object type or not. These operators are used for type checking and safety.

Examples

const stringTest = "test";
console.log(typeof stringTest); // returns: string

For more examples, please refer to this Complete typeOf, Instanceof examples.