TypeScript is an open-source language maintained and developed by Microsoft.
Basically, TypeScript adds additional syntax to JavaScript to support a tighter
integration with your editor. Catch errors early in your editor or in your CI/CD
pipeline, and write more maintainable code.
TypeScript is an open-source programming language developed and maintained by
Microsoft. It is a superset of JavaScript, meaning that any valid JavaScript code is
also valid TypeScript code. The primary addition TypeScript brings to JavaScript
is static typing, allowing developers to define types for variables, function
parameters, and return values.
This static typing enables the TypeScript compiler to perform type-checking and
catch type-related errors during development, before the code is executed. This
contrasts with JavaScript's dynamic typing, where type errors are typically
discovered at runtime. By identifying errors earlier, TypeScript helps improve code
reliability and maintainability, especially in large-scale applications.
Key features of TypeScript include:
Static Typing:
Explicitly define types for enhanced error detection and code clarity.
Advanced Features:
Support for object-oriented programming concepts like classes, interfaces, and
enums, which extend beyond standard JavaScript.
Tooling Support:
Enables richer tooling experiences in integrated development environments
(IDEs) with features like intelligent code completion, refactoring, and navigation.
Compatibility:
Fully compatible with existing JavaScript projects and can be seamlessly
integrated.
Transpilation:
TypeScript code is transpiled into plain JavaScript, ensuring compatibility across
various JavaScript environments, as browsers do not directly execute TypeScript.
TypeScript is widely adopted for building robust and scalable web applications,
particularly in frameworks like Angular and React, where its benefits for managing
complex codebases are highly valued.
a. Simple and Special Types
// Simple Types
let userName: string = "Neelima";
let age: number = 25;
let isLoggedIn: boolean = true;
// Special Types
let anything: any = "Can be anything";
anything = 42;
let notKnown: unknown = "Could be any type";
// void and never
function sayHello(): void {
console.log("Hello!");
}
function throwError(): never {
throw new Error("This is an error!");
}
b. Function Parameters and Return Types
function add(a: number, b: number): number {
return a + b;
}
function greet(name: string): void {
console.log("Hello, " + name);
}
let result = add(10, 5);
console.log("Addition Result:", result);
greet("Neelima");
c. Arrow Function with Optional, Default, and REST Parameters
// Arrow function with default and optional parameters
const greet = (name: string = "Guest", age?: number): string => {
return `Hello, ${name}${age ? ", age " + age : ""}`;
};
console.log(greet());
console.log(greet("Neelima", 22));
// Arrow function with REST parameters
const sum = (...numbers: number[]): number => {
return numbers.reduce((acc, curr) => acc + curr, 0);
};
console.log("Sum:", sum(10, 20, 30));
d. Classes, Constructors, Properties, Methods, Access Specifiers
class Person {
public name: string;
private age: number;
protected gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
public getDetails(): string {
return `Name: ${this.name}, Age: ${this.age}`;
}
}
const person1 = new Person("Neelima", 22, "Female");
console.log(person1.getDetails());
e. Namespaces and Modules
File: MathUtil.ts
export namespace MathUtil {
export function add(a: number, b: number): number {
return a + b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
}
File: Main.ts
typescript
CopyEdit
import { MathUtil } from "./MathUtil";
console.log("Addition:", MathUtil.add(5, 3));
console.log("Multiplication:", MathUtil.multiply(4, 2));
Note: Compile with tsc --module commonjs Main.ts and run using Node.js
f. Generics with Variables, Functions, and Constraints
// Generic variable
let value: Array<number> = [1, 2, 3];
// Generic function
function identity<T>(arg: T): T {
return arg;
}
console.log(identity<string>("Hello"));
console.log(identity<number>(100));
// Generics with constraint
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(item: T): void {
console.log("Length is:", item.length);
}
logLength("TypeScript");
logLength([1, 2, 3]);
To run TypeScript programs, follow these steps:
✅ Step 1: Install Node.js and TypeScript
1. Install Node.js (if not already installed):
👉 https://nodejs.org
2. Install TypeScript globally using npm:
npm install -g typescript
✅ Step 2: Create a TypeScript File
Create a file named example.ts:
// example.ts
let message: string = "Hello, TypeScript!";
console.log(message);
✅ Step 3: Compile TypeScript to JavaScript
Use the TypeScript compiler (tsc) to convert .ts to .js:
tsc example.ts
This creates a file called example.js in the same directory.
✅ Step 4: Run the JavaScript File with Node.js
Run the compiled JavaScript using Node:
node example.js
You should see:
CopyEdit
Hello, TypeScript!
✅ Optional: Use Watch Mode (Automatic Compilation)
tsc example.ts --watch
This watches the file and recompiles it automatically when you make changes.
✅ Optional: Initialize a TypeScript Project
For larger projects, create a tsconfig.json:
tsc --init
This lets you customize compiler options like target, module system, etc.