
πIntroduction to TypeScript
TypeScript Tutorial: TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript that adds static typing, interfaces, classes, and other object-oriented features. TypeScript code compiles into JavaScript and runs in the browser or in a Node.js environment.
Key Features of TypeScript:
β Statically typed language
β Supports Object-Oriented Programming (OOP)
β Compatible with JavaScript and ECMAScript features
β Helps in large-scale application development
π1. How to Install TypeScript
TypeScript Tutorial: To set up TypeScript on your system, follow these steps:
Step 1: Install Node.js
Download and install Node.js from the official website
Step 2: Verify Installation
TypeScript Tutorial: Open the command prompt and check if Node.js and npm are installed:
bash
node –version
npm –version
Step 3: Install TypeScript
TypeScript Tutorial: Use the following npm command to install TypeScript globally:
bash
npm install -g typescript
For a project-specific installation:
bash
npm install –save typescript
Step 4: Verify TypeScript Installation
TypeScript Tutorial: Check the installed TypeScript version:
bash
tsc –version
π2. Writing and Compiling TypeScript Code
Create a TypeScript file (test.ts):
typescript
function add(x: number, y: number): number {
return x + y;
}
console.log(add(5, 10));
Compiling TypeScript Code to JavaScript
Run the following command:
bash
tsc test.ts
This generates a JavaScript file (test.js), which can be executed using:
bash
node test.js
π3. TypeScript Variables & Data Types
TypeScript Tutorial: TypeScript is a strongly typed language with various data types:
Declaring Variables
typescript
let name: string = “John”; // String
let age: number = 25; // Number
let isStudent: boolean = true; // Boolean
let scores: number[] = [80, 90, 100]; // Array
let anything: any = “Can be any type”; // Any type
Difference Between var, let, and const
- var: Function-scoped, allows re-declaration.
- let: Block-scoped, prevents re-declaration.
- const: Block-scoped, cannot be reassigned.
Example:
typescript
let x = 10;
if (true) {
let x = 20;
console.log(x); // Output: 20 (block scope)
}
console.log(x); // Output: 10
π4. TypeScript Arrays
TypeScript Tutorial: Arrays store multiple values of the same type.
Declaring an Array
typescript
let numbers: number[] = [10, 20, 30];
let names: string[] = [“Alice”, “Bob”, “Charlie”];
Accessing Array Elements
typescript
console.log(numbers[0]); // Output: 10
Array Methods
typescript
numbers.push(40); // Adds element
numbers.pop(); // Removes last element
numbers.sort(); // Sorts array
numbers.reverse(); // Reverses order
Looping Through Arrays
Using forEach:
typescript
numbers.forEach(num => console.log(num));
Using for…of:
typescript
for (let num of numbers) {
console.log(num);
}
π5. TypeScript Interfaces
TypeScript Tutorial: Interfaces define the structure of an object.
Example: Defining an Interface
typescript
interface Student {
name: string;
age: number;
isGraduated: boolean;
}
let student: Student = {
name: “Alice”,
age: 22,
isGraduated: false
};
console.log(student.name); // Output: Alice
π6. TypeScript Enums
TypeScript Tutorial: Enums define a set of named constants.
Example: Enum Declaration
typescript
enum Direction {
Up = 1,
Down,
Left,
Right
}
console.log(Direction.Up); // Output: 1
π7. TypeScript Classes & OOP Concepts
TypeScript Tutorial: TypeScript supports classes, inheritance, and constructors.
Creating a Class
typescript
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getDetails(): string {
return `${this.name} is ${this.age} years old.`;
}
}
let person1 = new Person(“John”, 30);
console.log(person1.getDetails()); // Output: John is 30 years old.
Class Inheritance
typescript
class Student extends Person {
rollNo: number;
constructor(name: string, age: number, rollNo: number) {
super(name, age);
this.rollNo = rollNo;
}
getStudentInfo(): string {
return `${this.name} (Roll No: ${this.rollNo}) is ${this.age} years old.`;
}
}
let student1 = new Student(“Alice”, 22, 101);
console.log(student1.getStudentInfo());
π8. Compiling TypeScript to JavaScript with ECMAScript Versions
TypeScript Tutorial: By default, TypeScript compiles to ES3. To specify a target version:
bash
tsc –target ES6 test.ts
For example, an arrow function remains unchanged in ES6 but converts to a regular function in ES3:
ES6 Code:
typescript
const addNumbers = (a: number, b: number) => a + b;
Compiled ES3 Code:
javascript
var addNumbers = function (a, b) {
return a + b;
};
Complete SEO-Optimized Content:
πUnderstanding TypeScript Access Modifiers, Interfaces, Functions, Enums & Modules
TypeScript Tutorial: TypeScript is a powerful superset of JavaScript that introduces static typing, interfaces, and object-oriented programming features. In this guide, we will cover:
- Access Modifiers (public, private, protected)
- Interfaces and their usage in TypeScript
- Functions β including optional parameters, default values, and arrow functions
- Enums β numeric and string-based enums in TypeScript
- Modules β import/export features and their role in TypeScript
Let’s dive deep into each topic with examples.
π1. Access Modifiers in TypeScript
TypeScript Tutorial: Access modifiers control the visibility of properties and methods inside a class. TypeScript supports three main access modifiers:
- Public β Accessible anywhere, including outside the class.
- Private β Accessible only inside the class, not in derived classes.
- Protected β Accessible inside the class and in derived classes, but not outside.
Example: Access Modifiers in TypeScript
typescript
class Person {
protected name: string;
protected age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
private getName(): string {
return this.name;
}
getDetails(): string {
return “Name is ” + this.getName();
}
}
class Student extends Person {
tmarks: number;
constructor(name: string, age: number, tmarks: number) {
super(name, age);
this.tmarks = tmarks;
}
getMarks(): number {
return this.tmarks;
}
getFullName(): string {
return this.name;
}
}
β Key Takeaways:
- private members cannot be accessed outside the class or in derived classes.
- protected members can be accessed inside the class and subclasses but not outside.
- public members are accessible everywhere.
π2. Interfaces in TypeScript
TypeScript Tutorial: An interface in TypeScript defines a structure that an object should follow. It helps in enforcing type safety and reducing errors.
Syntax of an Interface:
typescript
interface Dimension {
width: string;
height: string;
}
Example: Using an Interface with a Variable
typescript
let imageSize: Dimension = {
width: “100px”,
height: “200px”
};
Example: Using an Interface in a Function
typescript
function getDimension(): Dimension {
return {
width: “300px”,
height: “250px”
};
}
Example: Class Implementing an Interface
typescript
interface Shape {
width: string;
height: string;
getWidth(): string;
}
class Rectangle implements Shape {
width: string;
height: string;
constructor(width: string, height: string) {
this.width = width;
this.height = height;
}
getWidth() {
return this.width;
}
}
β Key Benefits of Interfaces:
- TypeScript Tutorial: Ensure consistency in object structure.
- Improve code readability and maintainability.
- Can be implemented by classes, functions, or variables.
π3. Functions in TypeScript
TypeScript Tutorial: Functions in TypeScript can have explicit return types, optional parameters, default values, and rest parameters.
Basic Function Syntax in TypeScript
typescript
function add(a: number, b: number): number {
return a + b;
}
Optional Parameters in a Function
typescript
function getName(firstname: string, lastname?: string): string {
return firstname + (lastname || “”);
}
Assigning Default Values to Parameters
typescript
function getName(firstname: string, lastname: string = “Smith”): string {
return firstname + ” ” + lastname;
}
Using Rest Parameters
typescript
function testFunc(a: string, …args: string[]): string {
return a + args.join(” “);
}
β Key Benefits of TypeScript Functions:
- TypeScript Tutorial: Strong type checking reduces runtime errors.
- Optional parameters make functions flexible.
- Default parameters ensure fallback values.
- Rest parameters handle dynamic arguments efficiently.
π4. TypeScript Enums
TypeScript Tutorial: An Enum is a special type in TypeScript that allows defining a set of named constants.
Example: Numeric Enum
typescript
enum Directions {
North,
South,
East,
West
}
console.log(Directions.North); // Output: 0
Example: Enum with Custom Numeric Values
typescript
enum Directions {
North = 5,
South, // 6
East, // 7
West // 8
}
Example: String Enums
typescript
enum Directions {
North = “N”,
South = “S”,
East = “E”,
West = “W”
}
console.log(Directions.North); // Output: “N”
β Key Benefits of Enums:
- Improve code readability by using meaningful names instead of numbers.
- Avoid magic numbers in your code.
- Can be numeric or string-based.
π5. Modules in TypeScript
TypeScript Tutorial: Modules in TypeScript help in organizing code and avoiding global namespace pollution. They are used to import/export functionalities across files.
Exporting a Variable in TypeScript
typescript
// file: test1.ts
export let age: number = 25;
Importing the Exported Variable
typescript
// file: test2.ts
import { age } from “./test1”;
console.log(age); // Output: 25
Exporting a Class in TypeScript
typescript
// file: Customer.ts
class Customer {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getName(): string {
return this.name;
}
}
export = Customer;
Importing a Class Using require
typescript
// file: testCustomer.ts
import Customer = require(“./Customer”);
let customer = new Customer(“Alice”, 28);
console.log(customer.getName());
β Key Benefits of Modules:
- Improve code maintainability.
- Avoid global variable conflicts.
- Allow better structuring of large applications.
πUsing TypeScript Modules, Namespaces, and Ambient Declarations with RequireJS
TypeScript Tutorial: TypeScript is a powerful superset of JavaScript that introduces strong typing, object-oriented programming features, and enhanced development tools. This guide covers:
- Converting TypeScript modules to JavaScript using RequireJS
- Using Namespaces in TypeScript
- Working with Ambient Declarations for third-party JavaScript libraries
1. Converting TypeScript Modules to JavaScript Using RequireJS
RequireJS is a module loader that allows you to load JavaScript modules dynamically. Below is a simple example of converting a TypeScript module to JavaScript and testing it using RequireJS.
Example: Converting testCustomer.ts to testCustomer.js
typescript
// testCustomer.ts
import { Customer } from “./Customer”;
let a = new Customer(“Harry”, 30);
alert(a.getName());
After compilation, the equivalent JavaScript file using RequireJS will be:
javascript
// testCustomer.js
define([“require”, “exports”, “./Customer”], function (require, exports, Customer) {
“use strict”;
exports.__esModule = true;
var a = new Customer(“Harry”, 30);
alert(a.getName());
});
Example: Converting Customer.ts to Customer.js
typescript
// Customer.ts
export class Customer {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getName(): string {
return this.name;
}
}
After compiling, the JavaScript output will be:
javascript
// Customer.js
define([“require”, “exports”], function (require, exports) {
“use strict”;
var Customer = /** @class */ (function () {
function Customer(name, age) {
this.name = name;
this.age = age;
}
Customer.prototype.getName = function () {
return this.name;
};
return Customer;
}());
return Customer;
});
Setting Up RequireJS to Run the Modules
TypeScript Tutorial: To test the modules, you need a main.js file that loads dependencies.
javascript
// main.js
define(function (require) {
var customer = require(“./Customer”);
var testCustomer = require(“./testCustomer”);
});
HTML File to Run RequireJS
html
<!DOCTYPE html>
<html>
<head>
<title>TypeScript Module Testing Using RequireJS</title>
<script data-main=”main” src=”require.js”></script>
</head>
<body>
<h3>Testing Modules Using RequireJS</h3>
</body>
</html>
π2. Using Namespaces in TypeScript
TypeScript Tutorial: Namespaces allow grouping related code, such as classes, interfaces, and functions, under a single logical unit.
Namespace Syntax in TypeScript
typescript
namespace NamespaceName {
export class ClassName {
// Class Implementation
}
export interface InterfaceName {
// Interface Implementation
}
export function FunctionName() {
// Function Implementation
}
}
Example: Creating a Namespace in TypeScript
typescript
namespace StudentSetup {
export interface StudDetails {
name: string;
age: number;
}
export function addSpace(str: string): string {
return str.split(“”).join(” “);
}
export class Student implements StudDetails {
name: string;
age: number;
constructor(studentdetails: StudDetails) {
this.name = studentdetails.name;
this.age = studentdetails.age;
}
getName(): string {
return this.name;
}
}
}
Accessing the Namespace
typescript
// testStudentSetup.ts
let a = new StudentSetup.Student({ name: “Harry”, age: 20 });
console.log(“The name is: ” + StudentSetup.addSpace(a.getName()));
Compiling Namespace Files
TypeScript Tutorial: You can compile multiple TypeScript files into one JavaScript file using:
sh
tsc –outFile namespace.js testnamespace.ts testStudentSetup.ts
Run the generated JavaScript file using Node.js:
sh
node namespace.js
Expected Output:
pgsql
The name is: H a r r y
π3. Using Ambient Declarations in TypeScript
TypeScript Tutorial: Ambient declarations allow TypeScript to use third-party JavaScript libraries without modifying them.
Syntax for Ambient Declarations
typescript
declare module ModuleName {
// Function, Interface, or Variable Declarations
}
Example: Using a Third-Party JavaScript Library
TypeScript Tutorial: Consider a JavaScript file testString.js with utility functions:
javascript
var StringChecks = {
isString: function (str) {
return typeof str === “string”;
},
convertToUpperCase: function (str) {
return str.toUpperCase();
},
convertToLowerCase: function (str) {
return str.toLowerCase();
},
convertToStringBold: function (str) {
return str.bold();
}
};
Creating an Ambient Module in TypeScript
TypeScript Tutorial: To use testString.js in TypeScript, create a declaration file tstring.d.ts:
typescript
declare module TestString {
export interface StringsFunc {
isString(str: string): boolean;
convertToUpperCase(str: string): string;
convertToLowerCase(str: string): string;
convertToStringBold(str: string): string;
}
}
declare var StringChecks: TestString.StringsFunc;
Using the Ambient Module in TypeScript
typescript
/// <reference path=”tstring.d.ts”/>
let str1 = StringChecks.isString(“Hello World”);
console.log(str1);
let str2 = StringChecks.convertToUpperCase(“hello world”);
console.log(str2);
let str3 = StringChecks.convertToLowerCase(“HELLO”);
console.log(str3);
let str4 = StringChecks.convertToStringBold(“Hello World”);
console.log(str4);
Compiling and Running the Code
sh
tsc test.ts
node test.js
Expected Console Output:
bash
true
HELLO WORLD
hello
<b>Hello World</b>
πUnderstanding the Difference Between =, ==, and === in JavaScript
TypeScript Tutorial: JavaScript provides three different operators for assignment and comparison:
- = (Assignment Operator) β Assigns values to variables
- == (Equality Operator) β Compares values after type conversion
- === (Strict Equality Operator) β Compares both values and data types
In this guide, weβll explore each operator in detail with examples to understand how they work.
π1. What is = in JavaScript? (Assignment Operator)
TypeScript Tutorial: The = operator is used to assign a value to a variable. The value on the right side is assigned to the variable on the left.
Example of = in JavaScript:
html
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Assignment Operator</h2>
<p>a = 2, b = 5, calculate c = a + b, and display c:</p>
<p id=”demo”></p>
<script>
var a = 2;
var b = 5;
var c = a + b;
document.getElementById(“demo”).innerHTML = c;
</script>
</body>
</html>
Output:
r
a = 2, b = 5, calculate c = a + b, and display c:
7
Key Takeaways:
β = assigns a value to a variable.
β It does not compare values.
π2. What is == in JavaScript? (Equality Operator – Loose Comparison)
TypeScript Tutorial: The == operator compares two values but ignores the data type. If the types are different, JavaScript tries to convert them before making the comparison.
Example of == in JavaScript:
html
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Equality Operator</h2>
<p id=”demo”></p>
<script>
var a = 10;
document.getElementById(“demo”).innerHTML = (a == “10”);
</script>
</body>
</html>
Output:
arduino
true
Explanation:
- a == “10” returns true because JavaScript converts the string “10” to a number before comparison.
Key Takeaways:
β == performs type conversion before comparison.
β “10” == 10 returns true because JavaScript converts “10” into a number.
β false == 0 returns true because false is converted to 0.
π3. What is === in JavaScript? (Strict Equality Operator)
TypeScript Tutorial: The === operator (strict equality) compares both value and data type. It does not perform type conversion.
Example of === in JavaScript:
html
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strict Equality Operator</h2>
<p id=”demo”></p>
<script>
var x = 10;
document.getElementById(“demo”).innerHTML = (x === “10”);
</script>
</body>
</html>
Output:
arduino
false
Explanation:
- x === “10” returns false because 10 is a number and “10” is a string, so they are not strictly equal.
Key Takeaways:
β === checks both value and type.
β “10” === 10 returns false because “10” is a string and 10 is a number.
β false === 0 returns false because false is a boolean and 0 is a number.
π4. Key Differences Between =, ==, and === in JavaScript
Operator | Type | Purpose | Example | Output |
= | Assignment Operator | Assigns a value to a variable | a = 10; | a is assigned the value 10 |
== | Equality Operator (Loose) | Compares values after type conversion | “10” == 10 | true |
=== | Strict Equality Operator | Compares values and types | “10” === 10 | false |
π5. Summary of Differences
Feature | = (Assignment) | == (Equality) | === (Strict Equality) |
Purpose | Assigns a value | Compares values (with type conversion) | Compares values & types |
Type Checking? | No | No (performs conversion) | Yes |
Example | a = 5 | “5” == 5 (true) | “5” === 5 (false) |
Comparison Type | Not applicable | Loose Comparison | Strict Comparison |
π6. When to Use =, ==, and ===?
β Use = when you need to assign values to variables.
β Use == only if type conversion is acceptable (not recommended for strict coding).
β Use === for strict comparisons to avoid unintended type conversions.
π7. Common Pitfalls & Best Practices
Mistake 1: Using == Instead of ===
javascript
if (“0” == 0) {
console.log(“Equal”);
}
β Better Approach: Use === to avoid unwanted type conversion.
javascript
if (“0” === 0) {
console.log(“Equal”);
} else {
console.log(“Not Equal”);
}
Output:
mathematica
Not Equal
Mistake 2: Confusing = with ==
javascript
var x = 5;
if (x = 10) { // Mistake: Assignment instead of comparison
console.log(“True”);
}
β Better Approach: Always use === for comparisons.
javascript
if (x === 10) {
console.log(“True”);
}
π8. Final Thoughts
- = is used for variable assignment.
- == performs loose equality (with type conversion).
- === ensures strict equality by checking both value and type.
For better code quality and fewer bugs, always prefer === over == unless you explicitly need type coercion.
πConclusion
- TypeScript Tutorial: RequireJS is useful for loading TypeScript modules dynamically in JavaScript.
- Namespaces help in organizing TypeScript code effectively.
- Ambient Declarations allow seamless integration with third-party JavaScript libraries.
Using these techniques, you can improve the modularity, maintainability, and efficiency of your TypeScript projects.