- TypeScript is an open-source programming language developed by Anders Hejlsberg at Microsoft in 2012.
- TypeScript is not a new programming language; it is a superset of JavaScript, which means it adds additional features on top of JavaScript, such as :
- Type annotations
- Compile-time error checking
- Better tooling support
- Interfaces
- Generics and more
- TypeScript is not executed directly by browsers or runtime environments.
- Instead, it is compiled ( transpiled ) into plain JavaScript ( Vanilla JavaScript ), which can run in any JavaScript environment.
- TypeScript helps developers write more robust, maintainable, and error-free code, especially for large-scale applications.
- TypeScript allows developers to define types for variables, function parameters, and return values at compile time.
- This helps catch errors during development rather than at runtime.
- For example, if a variable is defined as a
number, assigning astringto it will produce a compile-time error. - This improves code reliability and maintainability.
- TypeScript is a superset of JavaScript, which means all valid JavaScript code is also valid TypeScript code.
- Developers can gradually adopt TypeScript in existing JavaScript projects without rewriting the entire codebase.
- Even when types are not explicitly defined, TypeScript can automatically infer the type based on the assigned value.
- This reduces the need for extra type annotations while still providing type safety.
- TypeScript provides Interfaces and Type Aliases to define the structure of objects and custom types.
- This helps maintain consistency across an application and ensures that objects follow the required structure.
- TypeScript supports OOP concepts such as :
- Classes
- Inheritance
- Encapsulation
- Access Modifiers (
public,private,protected)
- This makes it suitable for building large-scale and enterprise-level applications.
- TypeScript provides excellent support for modern code editors with features such as :
- Auto-completion
- Compile-time error detection
- IntelliSense ( smart code suggestions )
- Refactoring support
- These features improve developer productivity and reduce bugs.
- TypeScript fully supports JavaScript's ecosystem, including ES Modules.
- Developers can easily use existing JavaScript libraries and packages in TypeScript projects.
- Most popular libraries provide TypeScript type definitions for better development experience.
- TypeScript is widely used for building modern web applications.
- Popular frameworks such as Angular, React, and Vue.js support TypeScript.
- TypeScript can be used to build RESTful APIs and backend applications.
- It is commonly used with Node.js for scalable server-side development.
- TypeScript can be used to develop browser-based and cross-platform games.
- Its strong typing helps manage large and complex game codebases.
- TypeScript can be used to build desktop applications using frameworks such as Electron.
- Applications can run on Windows, macOS, and Linux.
- TypeScript is commonly used in hybrid mobile app frameworks.
- It helps build cross-platform mobile applications that run on both Android and iOS from a single codebase.
npm install -g typescript
- npm ( Node Package Manager ) is a command-line tool ( CLI ) used to install, uninstall, update, and manage JavaScript packages and modules.
node index.ts→ Generally not used in the traditional TypeScript workflow because Node.js executes JavaScript files.tsc index.ts→ Compiles a TypeScript file into JavaScript.ts-node index.ts→ Compiles and executes a TypeScript file directly.tsc index.ts -w→ Watches TypeScript files and automatically recompiles them whenever changes are detected.
- Type annotations allow you to explicitly specify the type of a variable, parameter, or return value.
- They help TypeScript perform compile-time type checking and catch errors early.
- Type annotations improve code readability, reliability, and maintainability.
// Primitive Types
const username: string = "sandeepahirwar";
const userID: number = 1714510036;
const isActive: boolean = true;
const email: null = null;
const phone: undefined = undefined;
console.log("Username :", username);
console.log("User ID :", userID);
console.log("Is Active? :", isActive);
console.log("Email :", email);
console.log("Phone :", phone);
// Array
const array: string[] = ["HTML", "CSS", "JS"];
console.log("Array :", array);
// Tuple
const tuple: [number, string] = [1714510036, "Sandeep Ahirwar"];
console.log("Tuple :", tuple);
// Any
const random: any = "XYZ@123";
console.log("Random :", random);
// Unknown
const address: unknown = "Unknown";
console.log("Address :", address);
// Object
const fruit: { name: string; price: number } = {
name: "Apple",
price: 100,
};
console.log("Fruit :", fruit);
// Union Type
let ID: string | number = "17CSECS1005";
ID = 1714510036;
console.log("ID :", ID);
// Function
function greet(name: string): string {
return `Hello, ${name}`;
}
console.log(greet("Sandeep Ahirwar"));
// Void
function display(message: string): void {
console.log(message);
}
display("The Quick Brown Fox Jumps Over The Little Lazy Dog");
// Never
function throwError(message: string): never {
throw new Error(message);
}
- Type Inference is a feature in TypeScript that automatically determines the type of a variable based on its assigned value.
- It reduces the need for explicit type annotations.
- TypeScript uses the inferred type for compile-time type checking.
- This helps maintain type safety while writing less code.
// Primitive Types
const username = "sandeepahirwar";
const userID = 1714510036;
const isActive = true;
const email = null;
const phone = undefined;
console.log("Username :", username);
console.log("User ID :", userID);
console.log("Is Active? :", isActive);
console.log("Email :", email);
console.log("Phone :", phone);
// Array
const array = ["HTML", "CSS", "JS"];
console.log("Array :", array);
// Object
const fruit = {
name: "Apple",
price: 100,
};
console.log("Fruit :", fruit);
// Function
function greet(name: string) {
return `Hello, ${name}`;
}
console.log(greet("Sandeep Ahirwar"));
- The
+operator can be used for both numeric addition and string concatenation. - For
-,*,/,%, and**operators, both operands must be of type number.
console.log(10 + "5");
console.log(10 + 5);
console.log(10 - 5);
console.log(10 * 5);
console.log(10 / 5);
console.log(10 % 5);
console.log(10 ** 5);
- Assignment operators and shorthand assignment operators are the same as in JavaScript.
- In relational operators, both operands should have the same type.
console.log(10 < 15);
console.log("10" < "15");
- In logical operators, the first operand must be
true,false,1, or0( boolean-compatible values ).
console.log(1 && 5);
console.log(0 && 5);
console.log(true && 5);
console.log(false && 5);
- Bitwise operators, conditional ( ternary ) operators, increment (
++), and decrement (--) operators work the same way as in JavaScript.
const n: number = 9;
console.log(n % 2 === 0 ? `${n} is an Even Number` : `${n} is an Odd Number`);
const number: number = 11;
if (number < 2) {
console.log(`${number} is not a Prime Number`);
} else {
let isPrime: boolean = true;
for (let divisor = 2; divisor <= Math.sqrt(number); divisor++) {
if (number % divisor === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log(`${number} is a Prime Number`);
} else {
console.log(`${number} is not a Prime Number`);
}
}
// Function Declaration
function greet(): void {
console.log("From greet(), Good Morning!");
}
greet();
// Function with Parameters
function greetUser(firstName: string): void {
console.log(`From greetUser(), Good Morning ${firstName}!`);
}
greetUser("Sandeep");
// Function with Return Type
function sum(A: number, B: number): number {
return A + B;
}
console.log("From sum(), 9 + 11 =", sum(9, 11));
// Optional Parameters
function introduction(name: string, age?: number): void {
console.log(`From introduction(), My name is ${name}.`);
}
introduction("Sandeep Ahirwar");
// Default Parameters
function welcome(name: string = "Friends"): void {
console.log(`From welcome(), Welcome ${name}!`);
}
welcome();
// Arrow Function
const addition = (A: number, B: number): number => {
return A + B;
};
console.log("From addition(), 9 + 11 =", addition(9, 11));
// Function Expression
const multiplication = function (A: number, B: number): number {
return A * B;
};
console.log("From multiplication(), 9 * 11 =", multiplication(9, 11));
// Rest Parameters
function findTotal(...numbers: number[]): number {
return numbers.reduce((total, number) => (total += number), 0);
}
console.log("From findTotal(), 1 + 2 + 3 + 4 + 5 =", findTotal(1, 2, 3, 4, 5));
// Anonymous Function
setTimeout(function () {
console.log("From (), Executed!");
}, 2000);
// Recursive Function
function factorial(n: number): number {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log("From factorial(), 5! =", factorial(5));
// Number Array
const numbers: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log("Number :", numbers);
// String Array
const fruits: string[] = ["Apple", "Banana", "Coconut", "Date"];
console.log("Fruits :", fruits);
// Boolean Array
const flags = [true, false];
console.log("Flags :", flags);
// Generic Array Syntax
const marks: Array<number> = [100, 200, 300];
console.log("Marks :", marks);
// Union Type Array
const values: (string | number)[] = [
"PI",
3.141592653589793,
"E",
2.718281828459045,
];
console.log("Values :", values);
const data: (string | number | boolean)[] = ["PI", 3.141592653589793, true];
console.log("Data :", data);
// Complex Union Type Array
const information: (string | number | boolean | number[])[] = [
"PI",
3.141592653589793,
true,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
];
console.log("Information :", information);
const poem = `She said, "Dream on," held a 'rose', and wrote hope in the sand.`;
console.log(poem);
- Tells TypeScript to treat a value as a specific type.
- Affects only type checking.
- Does not change the value at runtime.
Syntax
value as Type
<Type>value
const array: any = [false, true, 2, "three", 4, 5, "six", 7, 8, 9];
console.log(
(array as number[]).filter((n) => typeof n === "number" && n % 2 === 0),
);
const fruit: any = "Apple";
console.log((fruit as string).toLocaleLowerCase());
var array: any = [false, true, 2, "three", 4, 5, "six", 7, 8, 9];
console.log(
(<number[]>array).filter((n) => typeof n === "number" && n % 2 === 0),
);
var fruit: any = "Apple";
console.log((fruit as string).toLocaleUpperCase());
A TypeScript object type alias provides a way to assign a name to a specific object structure.
Benefits :
- Improves code readability and maintainability.
- Allows the reuse of complete type definitions.
Syntax :
- Use the
typekeyword. - Specify the alias name.
- Define the object structure.
type Student = {
ID: number;
name: string;
CGPA: number;
education: string[];
};
const student: Student = {
ID: 1714510036,
name: "Sandeep Ahirwar",
CGPA: 6.9,
education: ["B.Tech", "SRGI Jhansi"],
};
console.log(student);
An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that an entity must follow.
Interfaces define properties, methods, and events, which are the members of the interface.
Benefits :
- Provides a standard structure for implementing objects.
- Improves code consistency and maintainability.
Key Points :
- Interfaces contain only member declarations.
- It is the responsibility of the implementing object to define the members.
- Implementing objects must follow the structure defined by the interface.
interface Employee {
ID: number;
name: string;
designation: string;
}
const employee: Employee = {
ID: 1623157,
name: "John Doe",
designation: "Software Engineer",
};
console.log(employee);
Readonly properties cannot be modified after they are initialized. They help prevent accidental changes to object properties.
Benefits :
- Improves data integrity.
- Prevents unintended modifications.
type Fruit = {
readonly name: string;
price: number;
};
const fruit: Fruit = {
name: "Apple",
price: 100,
};
console.log(fruit);
interface Animal {
readonly name: string;
weight: number;
}
const animal: Animal = {
name: "Elephant",
weight: 870,
};
console.log(animal);
Optional properties are not required when creating an object. They are defined using the ? operator after the property name.
Benefits :
- Provides flexibility when defining objects.
- Allows properties to be omitted when they are not needed.
type Language = {
name: string;
origin?: number;
};
const language: Language = {
name: "Hindi",
};
console.log(language);
interface Friend {
name: string;
age?: number;
}
const friend: Friend = {
name: "Himanshu Savita",
};
console.log(friend);
- A class is a blueprint for creating objects.
- An object is an instance of a class.
public– Accessible from anywhere.protected– Accessible within the class and its derived classes.private– Accessible only within the class.
Example :
class Parent {
public A = 10;
protected B = 20;
private C = 30;
display() {
console.log(
`In display() of Parent Class, A = ${this.A}, B = ${this.B} and C = ${this.C}`,
);
}
}
class Child extends Parent {
show() {
console.log(`In show() of Child Class, A = ${this.A} and B = ${this.B}`);
}
}
const object = new Child();
object.display();
object.show();
console.log(`From Object, A = ${object.A}`);
An abstract class is a class that cannot be instantiated directly. It is used as a base class for other classes.
Key Points :
- Cannot create objects of an abstract class.
- Can contain both abstract and regular methods.
- Derived classes must implement all abstract methods.
Example :
abstract class Shape {
display(shape: string) {
console.log(`Shape : ${shape}`);
}
abstract area(radius: number): number;
}
class Circle extends Shape {
area(radius: number): number {
return 3.14 * Math.pow(radius, 2);
}
}
const circle = new Circle();
circle.display("Circle");
console.log(`Area : ${circle.area(5)}`);
A Promise is an object that represents the eventual completion or failure of an asynchronous operation.
- Pending – The operation is still in progress.
- Fulfilled – The operation completed successfully.
- Rejected – The operation failed.
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise is resolved.");
reject("Promise is rejected.");
}, 2000);
});
promise
.then((value) => {
console.log(value);
})
.catch((error) => {
console.log(error);
});