Operators in TypeScript

We perform a function on a piece of data using operators. This piece of data on which a function is performed is called operand(s).

There are various operators divided into multiple categories:

Arithmetic Operators

Arithmetic operators are used to perform operations on numerical operands. Below are some arithmetic operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
+ Addition. This will return the sum of two operands a + b = 30
Subtraction. This will return the difference between two operands b-a=10
* Multiplication. This will return the product of two operands a*b=200
/ Division. This will return quotient b/a=2
% Modulus. This will return remainder b%a=0
++ Increment. This will increment the value of operand by one a++ will return 11
Decrement. This will decrement the value of operand by one a– will return 9
Relational Operators

These operators define the relationship between two operands and returns true or false. Below are some relational operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
> Greater Than (b > a) will return true
< Less Than (a < b) will return true
>= Greater than or equal to (a >= b) will return false
<= Less than or equal to (a <= b) will return true
== Equal To (a == b) will return false
!= Not Equal to (a != b) will return true
Logical Operators

These operators are used to combine two or more conditions. They also return boolean value, true or false. Below are some logical operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
&& AND. This will return true if all the conditions are true ((a < b) && (a != b)) will return true as both these conditions are true
|| OR. This will return true if any one of the condition is true ((a < b) && (a == b)) will return true as first condition is true
! NOT. This will return the opposite of the condition result (!(a < b)) will return false.
Assignment Operators

These operators are used to assign values to a variable. Below are some assignment operators with example. Let’s take two variables: a=10, b=20.

Operator Description Example
= Assignment. Assigns the value of right side operand to left side operand b = a (This will assign 10 to variable b)
+= Add and Assign. Add value of right operand to left operand and then assigns the sum to left operand a += b (Adds 20 to 10 and then assigns sum(30) to variable a)
-= Subtract and Assign. Subtract right operand from left operand and then assigns the difference to left operand b -= a (Subtracts 10 from 20 and assigns the difference(10) to variable b)
*= Multiply and Assign. Multiply right operand to left operand then assigns the product to left operand. a *= b (Multiplies a and b and assigns the product(200) to a)
/= Divide and Assign. Divides left operand with right operand and assigns quotient to left operand b /= a (Divides b by a and assigns quotient(2) to b)
Negation Operator (-)

It will change the sign of the integer value. That is, it will change positive value to negative value and negative value to positive value.

var num1:number = 10;
var num2 = -num1;
console.log("num1: " + num1 + "; num2: " + num2);
Output: num1: 10; num2: -10

After executing, num1 will be 10 and num2 will be -10.

Concatenation Operator (+)

This operator is applied on string values to concatenate two strings together. We can concatenate multiple strings in one sentence using multiple concatenation operators between two strings.

var fullName:string="Hello" + " Akanksha" + " Garg";
console.log(fullName);
Output: Hello Akanksha Garg

Kindly note that concatenation operator does not add a space between two strings, you have to explicitly place a space like I did in my example.

typeof Operator

This operator returns the data type of a variable.

var firstname="Akanksha";
console.log(typeof(firstname));
Output: string

Variables in TypeScript

    • Variable is a named space in memory that stores a value.
    • Variables can include characters or digits or both. But they cannot begin with digits.
    • They cannot contain special symbols except underscore(_) or dollar sign($).
    • We cannot use keywords as variables and they must be unique within a scope.
    • They are case-sensitive and cannot contain spaces.
    • Some examples of Identifiers are: firstName, last_Name, number1 etc.
    • You should declare a variable using a data type before you use it.
    • Use var keyword to declare a variable.
    • For example: var value:string=”Hello”;
var value:string=”Hello”; Declaring a variable of a particular data type and storing a value in it.
var value:string; Declaring a variable of a particular data type. As we are not assigning a value to it, by default undefined is assigned to it
var value=”Hello”; Declaring a variable and storing a value in it. Data type of the variable is determined by the type of value stored in it. Hence it will be of string type
var value; Declaring a variable. As nothing is specified, the data type will be any and value will be undefined

Data Types in TypeScript

Data Types represent different types of values supported by a language. This will check if a value is valid or not before assigning it to a variable. This ensures the behavior of the code.

Any Type

The any data type is the super data type of all the data types in TypeScript. It denotes a dynamic type. We can assign any type of value in this type of variable. We use this data type when we want to opt out of type checking for a variable.

Built-In Data Types

Data Type Keyword Description
Number number It can be both integer and fraction value
String string Unicode character values
Boolean boolean logical values, true or false
Void void used as functions return types when we do not want to return anything
Null null leave the variable blank and not assign any value to it
Undefined undefined denotes value given to all uninitialized variables.

There is a difference between null and undefined. They cannot only be used to assign values to the variables. A variable initialized with undefined means that the variable has no value or object assigned to it while null means that the variable has been set to an object whose value is undefined.

User-Defined Data Types

These includes Enums, classes, interfaces, arrays and tuples.

Keywords in TypeScript

We cannot use keywords as identifier names.

Below is a list of few keywords in TypeScript:

break case var module
public null in finally
any new package continue
as type if number
private super for return
do try implement extends
switch typeof get else
export void new false
function let const catch
break case var yield
interface static true this
while enum instanceof string
throw any

Sample program using TypeScript

Before going further, look here for some basic concepts of TypeScript.

Below is a sample program using TypeScript. Save this program with, say HelloWorld.ts

   
var firstname:string = "Akanksha"
console.log(firstname)

When compiled, this code will be converted to JavaScript and a new file is created in the same folder with the same name, but with .js extension (HelloWorld.js)

   
var value = "Hello World!!";
console.log(value);

Open NodeJS Command Prompt.
Go to the folder where you have saved your TypeScript file.
Write tsc HelloWorld.ts
Above code will compile your code in .js file.

Then Write node HelloWorld.js
Above code will execute .js file and displays the result. Remember to use .js as extension.

Basic Concepts and Syntax of TypeScript

  • A TypeScript code comprise of variables, functions, statements, comments etc.
  • The identifiers, such as variables and function name, can include characters or digits or both. But they cannot begin with digits.
  • Identifiers cannot contain special symbols except underscore(_) or dollar sign($). We cannot use keywords as identifiers and they must be unique within a scope. They are case-sensitive and cannot contain spaces. Some examples of Identifiers are: firstName, last_Name, number1 etc.
  • TypeScript is case-sensitive that means it can differentiate between uppercase and lowercase. For example, name and Name are two different identifiers in TypeScript.
  • Each line of code is called a statement. Semicolon (;) are optional at the end of the statement.
  • If you include multiple statements in a single line, then those statements must be separated using semicolon.
  • There are two types f comments in TypeScript:
    • Single Line Comments(//): Any text between // and the end of the line is considered as comment and will not be executed.
    • Multiple Line Comments(/* */): Any text between /* and */ are considered as comment even if it spans multiple lines and will not be executed.

TypeScript Environment Setup

There are multiple ways to setup the environment for TypeScript.

I will be using Visual Studio Code to create applications using TypeScript.

Download and install Node.js as per your system configuration.

Open Node.js command prompt. Use it to install TypeScript.

If you get any error while using below command, verify whether you have installed Node.js crrectly or not. Use node -v command to get the version number of Node.js and to verify the successful installation of Node.js.

Download and install Visual Studio Code as per your system configuration.

Introduction to TypeScript

  • TypeScript is a superset of JavaScript. TypeScript code is compiled into JavaScript code. TypeScript = JavaScript + Additional Features.
  • TypesScript files are saved with .ts. extension.
  • Any valid .js file can be renamed to .ts.
  • Compiled TypeScript can be consumed from any JavaScript code.
  • It is pure Object Oriented Language like C# or Java with classes, objects, interfaces, inheritance etc.
  • To learn TypeScript, you should have basic knowledge of JavaScript and Object Oriented concepts.
  • TypeScript is portable across browsers, devices and operating systems. It can run on any environment where JavaScript can run.
  • TypeScript provides with error-checking feature. It compiles the code and generate compilation error, if there are any syntax errors.
  • TypeScript is strongly typed script. Variable declared with no type can be inferred by TLS (TypeScript Language Service) based on its value.
  • TypeScript also supports  type definition for existing JavaScript libraries. TypeScript Definition file, .d.ts extension, provides definition for external JavaScript libraries.
  • When TypeScript is compiled, there is an option to create a declaration fie, which functions as an interface to the components in the compiled JavaScript.
  • Declaration files are similar to header files in C++.

Components of TypeScript

  • Language: It has syntax, keywords and type annotations.
  • TypeScript Compiler: TypeScript Compiler (TSC) converts the TypeScript code into JavaScript.
  • TypeScript Language Service: It exposes an additional layer around the core compiler pipeline that are editor-like applications.

Prevent page to automatically refresh after clicking a button

Generally when we click a Button on our page, button performs ts actions and the page gets reloaded to its original state. To do not refresh the page we add event.preventDefault(); at the end of our JavaScript function.

<button id="myBtn">Try it​</button> 
<p id="demo">
</p> 
<script>
document.getElementById("myBtn").addEventListener("click", function(){
    document.getElementById("demo").innerHTML = "Hello World";
    event.preventDefault();
});
</script> ​<br/>

Another code can be:

<button id="myBtn" onclick="test()">Try it​</button>
<p id="demo"> 
</p>
<script>
function test(){
    document.getElementById("demo").innerHTML = "Hello World";
    event.preventDefault();
}
</script> ​​<br/>
Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started