Array, Tuple, Union in TypeScript
Array:
Array use of variables to store values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type.
Declaring and Initializing Arrays
To declare an initialize an array in Typescript uses the following syntax:
let arrayName:datatype[] //declaration
arrayName=[1,2,3] //initialization
many way array declaration
Tuple:
We know that an array holds multiple values of the same datatype. But sometimes, we may need to store a collection of values of different data types in a single variable. Arrays will not provide this feature, but TypeScript has datatype called tuple to achieve this purpose.
We may want to represent a value as a pair of a string and a number:
Declare a tuple type
Initialize it
Initialize it incorrectly
Accessing an element outside the set of known indices fails with an error:
Destructuring a Tuple
Union:
we can define a variable that can have multiple types of values. Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars.
Example: Union Type Variable
Reference: https://www.typescriptlang.org/docs/handbook/basic-types.html https://www.javatpoint.com/
Typescript
What is Typescript?
Typescript is a strongly typed, object oriented, compiled language. Typescript is both a language and a set of tools. Typescript is a typed superset of JavaScript compiled to JavaScript. In other words, Typescript is JavaScript plus some additional features.
Typescript
- Is purely object oriented programming.
- Can be used for client-side and server-side development alike
- Offers a “compiler” that can convert to JavaScript-equivalent code
- Has an API for DOM manipulation
- Has a namespace concept by defining a “Module”
Value Types:
Type define different types of value. The values can be different type. Typescript provides data types as a part of its optional Type System.
Mainly typescript can be two types. One is build I types and another is user defined types.
Build in types: build in types means that types are already given or declared in typescript.
Variables:
What is variable?
- A named space in the memory that stores values
- Variables are the container for values in a program
Naming Rules for variables:
- Variable names can contain alphabets and numeric digits.
- They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
- Variable names cannot begin with a digit.
Declaration of variable:
Variable Scope:
- Global Scope− Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code.
- Class Scope− These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static. Static fields can be accessed using the class name.
- Local Scope− Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared.
here, global_num is a global variable, class_num is class variable and local_num is a local variable.
Operators in Typescript:
An operator defines some function that will be performed on the data. The data on which operators work are called operands.
There are different types of variables in typescript. they are-
- Arithmetic operators
- Logical operators
- Relational operators
- Bitwise operators
- Assignment operators
- Ternary/conditional operator
- String operator
- Type Operator
Arithmetic operators:
Arithmetic operators are the symbols that represent arithmetic math operations.
Arithmetic operators are- Addition(+),subtraction(-), multiplication(*), Division(/), Modulus(%), increment(++), decrement(–).
Logical operators:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value.
Relational operators:
Relational Operators test or define the kind of relationship between two entities. Relational operators return a Boolean value, i.e., true/ false.
Assignment operators:
Assignment operators are used to assign values to variables. This type of statement consists of a variable name, an assignment operator, and an expression.
Conditional operators:
This operator is used to represent a conditional expression. The conditional operator is also sometimes referred to as the ternary operator.
String operators:
- It is also called Concatenation operator (+).
- The + operator when applied to strings appends the second string to the first.
output will be: helloworld
Type Operators:
- It is a unary operator. This operator returns the data type of the operand.
output is: number
Decision making:
A decision-making construct evaluates a condition before the instructions are executed.
There are different types of conditional statement in typescript. They are…
- If statement.
- If else statement
- If else if statement
- Nested if statement
- Switch statement
If statement:
The if statement evaluates a condition and, if the condition’s result is true then execute a block of code that are inside the if statement.
example:
If else:
It also check the condition and when the condition is true , if statement will be executed otherwise else statement will be executed.
example:
If else if statement:
It can check more than one condition if first condition is true then execute first statement otherwise check another condition in else if then if true then execute else if statement if it is also false then execute else statement.
Nested if condition:
It will check the if condition then another condition will be given inside the if statement. Flowchart is given bellow-
Example:
output:
Switch statement:
The switch case statement is used when we have multiple options and we need to perform a different task for each option.
example:
output:
Loops in Typescript:
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages.
Types of loops:
There are different loops in typescript. They are given bellow-
Definite loop:
- A loop whose number of iterations are definite/fixed is termed as a definite loop. The for loopis an implementation of a definite loop.
for loop:
The for loop is an implementation of a definite loop. it given a fixed number for continue.
Different for loops:
- for loop
- for..of loop
- for..in loop
example:
While loop:
The while loop is another type of loop that checks for a specified condition before beginning to execute the block of statements. The loop runs until the condition value is met.
syntax: while(condition){statement}
example:
output:
Do while loop:
The do..while loop is similar to the while loop, except that the condition is given at the end of the loop. The do..while loop runs the block of code at least once before checking for the specified condition.
syntax: do{statement}while(condition)
example:
output:
Function:
Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code.
Defining a Function:
A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. Functions are defined using the function keyword.
syntax:
function function_name() { // function body }
Calling a function:
A function must be called so as to execute it. This process is termed as function invocation.
syntax: function_name();
Parameters in function:
Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function.
syntax:
function function_name (param1[:type], param2[:type], param3[:type])
Rest Parameters:
Rest parameters don’t restrict the number of values that you can pass to a function. In other words, rest parameters act as placeholders for multiple arguments of the same type. To declare a rest parameter, the parameter name is prefixed with three periods.
example:
Default parameter:
Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.
syntax:
function function_name(param1[:type],param2[:type] = default_value) { }
Note − A parameter cannot be declared optional and default at the same time.
example:
Anonymous function:
Functions that are not bound to an identifier (function name) are called as anonymous functions. These functions are dynamically declared at runtime.An anonymous function is usually not accessible after its initial creation.
syntax:
var res = function( [arguments] ) { … }
example:
Recursion:
Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop.
example:
Lambda function:
Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.
Example:
reference: https://www.tutorialspoint.com/typescript
Namespaces:
The namespace is used for logical grouping of functionalities. A namespace can include interfaces, classes, functions and variables to support a single or a group of related functionalities.
A namespace can be created using the namespace keyword followed by the namespace name. All the interfaces, classes etc. can be defined in the curly brackets { }.
Syntax:
How can we use namespace?
In this example, we have a namespace named studentcal in file studentcalc.ts. We want to use the feeCalc function in another program. That’s why export keyword should use before the desire function.
Now we want to use the studentcal namespace as well as feeCalc function to calculate a value in a new program app.ts using the reference just like below code.
If we run this app.ts using the following command we will get an error indicates “can’t find studentcal”.
To solve this problem, we have to combine this two files studentcalc.ts and app.ts. A file named out.js. will be created if we command this line-
We got a new file named out.js. Then we have to run this out.js and that will solve the problem.
Happy Coding!!!!!