Typescript Operators

typescript Jul 29, 2019

Operators

All the standard JavaScript operators are available within your TypeScript program.  This section describes operators that have special significance within TypeScript because of type restrictions or because they affect types.

Increment and Decrement

The increment (++) and decrement (--) operators can only be applied to variables of type any, number, or enum. This is mainly used to increase index variables in a loop or to update counting variables in your program. In these cases, you will typically be working with a number type. The operator works on variables with the any type, as no type checking is performed on these variables.

let counter = 0;
do { 
++counter;
}
while (counter < 10);
// 10 alert(counter);

When incrementing or decrementing an enumeration, the number representation is updated. above code shows how incrementing the size variable results in the next element in the enumeration and decrementing the size variable results in the previous element in the enumeration. Beware when you use this method as you can increase and decrease the value beyond the bounds of the enumeration.

enum Size {    S,    M,    L,    XL } 
var size = Size.S; ++size; console.log(Size[size]); // M
var size = Size.XL; --size; console.log(Size[size]); // L
var size = Size.XL; ++size; console.log(Size[size]); // undefined

Binary Operators

The operators in the following list are designed to work with two numbers. In TypeScript, it is valid to use the operators with variables of type number or any. Where you are using a variable with the any type, you should ensure it contains a number. The result of an operation in this list is always a number.

The plus (+) operator is absent from this list because it is a special case: a mathematical addition operator as well as a concatenation operator. Whether the addition or concatenation is chosen depends on the type of the variables on either side of the operator. code below shows, this is a common problem in JavaScript programs in which an intended addition results in the concatenation of the two values, resulting in an unexpected value. This will be caught in a TypeScript program if you try to assign a string to a variable of the number type, or try to return a string for a function that is annotated to return a number.

The rules for determining the type resulting from a plus operation are the following:

• If the type of either of the arguments is a string, the result is always a string.

• If the type of both arguments is either number or enum, the result is a number. • If the type of either of the arguments is any, and the other argument is not a string, the result is any. • In any other case, the operator is not allowed.

// 6: number 
const num = 5 + 1;

// '51': string 
const str = 5 + '1';

When the plus operator is used with only a single argument, it acts as a shorthand conversion to a number. The unary minus operator also converts the type to number and changes its sign

const str: string = '5';

// 5: number
const num = +str;

// -5: number
const negative = -str;

Logical Operators

Logical operators are usually used to test Boolean variables or to convert an expression into a Boolean value. This section explains how logical operators are used in TypeScript for this purpose, and how logical AND and logical OR operators can be used outside of the context of Boolean types.

NOT Operator

The common use of the NOT (!) operator is to invert a Boolean value: for example, if (!isValid) conditionally runs code if the isValid variable is false. Using the operator in this way does not affect the type system.

The NOT operator can be used in TypeScript in ways that affect types. In the same way the unary plus operator can be used as a shorthand method for converting a variable of any type to a number, the NOT operator can convert any variable to a Boolean type. This can be done without inverting the truth of the variable by using a sequence of two unary NOT operators (!!). Both are illustrated in code below. Traditionally, a single ! is used to invert a statement to reduce nesting in your code, whereas the double !! converts a type to a Boolean.

const truthyString = 'Truthy string';
let falseyString: string;

// False, it checks the string but inverts the truth
const invertedTest = !truthyString;

// True, the string is not undefined or empty 
const truthyTest = !!truthyString;

// False, the string is empty 
const falseyTest = !!falseyString;

When converting to a Boolean using this technique, the JavaScript type juggling rules apply. For this reason, it is worth familiarizing yourself with the concepts of “truthy” and “falsey” that apply to this operation. The term falsey applies to certain values that are equivalent to false when used in a logical operation. Everything else is “truthy” and is equivalent to true. The following values are “falsey” and are evaluated as false

var myProperty;
if (myProperty) {   

// Reaching this location means that...  
// myProperty is not null    
// myProperty is not undefined  
// myProperty is not boolean false
// myProperty is not an empty string   
// myProperty is not the number 0   
// myProperty is not NaN 

}

AND Operator.

The common use of the logical AND operator (&&) is to assert that both sides of a logical expression are true, for example, if (isValid && isRequired). If the left-hand side of the expression is false (or is falsey, meaning it can be converted to false), the evaluation ends. Otherwise, the right-hand side of the expression is evaluated.

The AND operator can also be used outside of a logical context because the right-hand side of the expression is only evaluated if the left-hand side is truthy., the console.log function is only called if the console object is defined. In the second example, the player2 variable is only set if there is already a player1 value. Where the result of the expression is assigned to a variable, the variable will always have the type of the right-hand expression.

// longhand 
if (console) { 
   console.log('Console Available'); }
// shorthand 
    console && console.log('Console Available');
    
const player1 = 'Martin';

// player2 is only defined if player1 is defined
    const player2 = player1 && 'Dan';
    
// 'Dan'
alert(player2);

OR Operator

The common use of the logical OR (||) operator is to test that one of two sides to an expression are true.  The left-hand side is evaluated first and the evaluation ends if the left-hand side is true. If the left-hand side is not true, the right-hand side of the expression is evaluated.

The less common use of the OR operator is to coalesce two values, substituting a value on the left with one on the right in cases where the left-hand value is falsey. . The result has the best common type between the two types in the expression.

// Empty strings are falsey 
  let errorMessages = '';
  
// result is 'Saved OK'
  let result = errorMessages || 'Saved OK';
  
// Filled strings are truthy 
   errorMessages = 'Error Detected';
   
// result is 'Error Detected' 
    result = errorMessages || 'Saved OK';
    
let undefinedLogger;

// if the logger isn't initialized, substitute it for the result of the right-    hand expression 
const logger = undefinedLogger || { log: function (msg: string) { alert(msg); } };

// alerts 'Message' logger.log('Message');

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning