Introduction to TypeScript: A Static Typed Superset of JavaScript
Step by step guide to installing and configuring typescript
What is typescript?
→ typeScript can be considered as a static typed superset of javaScript, that transpiles to javaScript application developed by providing a more traditional object-oriented programming experience.
What do you mean by transpile?
→ Transpilation is the process of converting source code of one programming language to another programming language.
- TypeScript code must be transpiled to JavaScript code to use it in an application.
- ECMAScript is trademarked scripting language specification.
- JavaScript implements ECMAScript specification.
- TypeScript implements ECMAScript specifications. Also, it implements its own features.
features of TypeScript:
- Static Typing: It adds static typing to JavaScript, due to which the readability of the code improves and helps in finding more early compilation errors than run time errors.
- Modules support: TypeScript provides an option to create modules to modularize the code for easy maintenance. Modules help in making the application scalable.
- Object-Oriented Programming: TypeScript supports Object-Oriented Programming features such as class, encapsulation, interface, inheritance and so on which helps in creating highly structured and reusable code.
- Open Source: TypeScript is open source. The source code of TypeScript can be downloaded from Github.
- Cross-Platform: It works across the platforms such as iOS, Android etc.
How to Install and configure typeScript?
To install TypeScript from the NPM repository, use the command
npm i -g typescript
To transpile a TypeScript file, use the command
tsc filename
Demo 1
Step 1. Create a folder and create a file “hello.ts”
console.log("Hello World");
Step 2. Run tsc command
tsc hello.ts
After running the tsc command you will be able to see generated hello.js file now you can run by node command.
node hello.js
Output:
Hello World
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
TypeScript compiler never runs your code, It just does type checking and converted into respective .js file.
TypeScript throws compilation error, and javaScript throws run-time error.
In typeScript, you can define how strict your typeScript is, So you need to write configuration for that inside tsconfig file.
How to generate tsconfig file or customize confugation for typeScript?
To generate tsconfig.json file, use this command
tsc --init
The compiler options for a TypeScript project can be configured in two ways:
- using tsconfig.json file.
- using tsc command along with the command line options
The widely used compiler options are
--module, --outFile, --outDir, --target and --watch.
How to declare a variable in typeScript?
Syntax:
let variableName : data_type = "data";
Example:
A string is used to assign textual values or template strings. String values are written in quotes — single or double.
let name: string = "Rahul";
let name: string = 'Rahul';
let name: string = ` template string `;
boolean is a data type that accepts only true or false as a value for the variable it is been declared.
let showImage: boolean = true;
number type represents numeric values. All TypeScript numbers are floating-point values.
let age : number = 24;
any type is used to declare a variable whose type can be determined dynamically at runtime with the value supplied to it. If no type annotation is mentioned while declaring the variable, any type will be assigned by default.
let screenSize: any;
screenSize = 13.97;
screenSize = "5.5-inch"; // It can acceptable because data type is any.
void is basically used to represent no data. A variable can be declared with void type as below:
let product: void = undefined;
let product: void = null;
//will throw error if --strictNullChecks is given as compiler option while compiling.
function displayProductDetails(): void {
console.log("Product category is Gadget");
}
In TypeScript, it is also possible to declare that a variable can take value belonging to one of the data types from a previously defined set. The set of data types are added using | symbol (union operator).
let unionVar: string | number | boolean;
unionVar = 'hello'; //no error
unionVar = 5; //no error
unionVar = true; //no error
unionVar = undefined; //will throw error as undefined is not mentioned in the union in line 1
Type Annotation is a way to enforce type restriction to a specific variable or a function. If a variable is declared with a specific data type and another type of value is assigned to the variable, a compilation error will be thrown.
Arrays:
- An array is used to store multiple values in a single variable.
- The values stored in an array can be easily accessed using the index position of the data stored in the array.
- TypeScript array is an object to store multiple values in a variable with a type annotation.
How to create an Array:
- Using datatype[] declaration:
//String array is created using string[] declaration
let manufacturers:string[] = ["Samsung","Apple","Sony"];
// Number array is created using number[] declaration
let marks: number[] = [34,45,56,67];
//It accepts any type of data
let products : any[] = ["Mobile",12500,true];
2. Using Array <type> declaration:
//String array is created using Array<type> declaration
let manufacturers:Array<string> = ["Samsung","Apple","Sony"];
// Number array is created using number[] declaration
let marks: Array<number> = [34,45,56,67];
//It accepts any type of data
let products : Array<any> = ["Mobile",12500,true];
Note: All the JavaScript array methods are supported in TypeScript also.
Tuple:
Tuple is a kind of array which accepts more than one predefined type of data. For example:
let productAvailable: [string, boolean] = ["Samsung Galaxy", true];
Here in above example, tuple productAvailable consists of two elements of type string, and boolean respectively.