1️⃣ TypeScript Syntax vs. JavaScript Syntax
TypeScript extends JavaScript, meaning you can write regular JavaScript code and add extra TypeScript features.
✔ JavaScript Code (Valid in TypeScript)
let message = "Hello, World!";
console.log(message);
✔ TypeScript Code with Type Annotations
let message: string = "Hello, World!";
console.log(message);
👉 Key difference: The : string specifies that message must always be a string.
2️⃣ Variables and Data Types in TypeScript
In TypeScript, you must define data types for variables.
🔹 Declaring Variables with Type Annotations
let name: string = "John"; // String type
let age: number = 25; // Number type
let isStudent: boolean = true; // Boolean type
✅ TypeScript enforces the correct data type, preventing unexpected errors.
🔹 Using let, const and var
Keyword | Scope | Reassignment Allowed? |
---|---|---|
let | Block | ✅ Yes |
const | Block | ❌ No |
var | Function | ✅ Yes (Avoid using it) |
Example:
let username: string = "Alice";
const PI: number = 3.14;
var country: string = "India"; // Not recommended in TypeScript
3️⃣ Functions in TypeScript
TypeScript functions must define input and output types.
🔹 Function with Parameters and Return Type
function addNumbers(a: number, b: number): number {
return a + b;
}
console.log(addNumbers(10, 20)); // Output: 30
✅ Explanation:
✔ a: number, b: number → Both parameters must be numbers.
✔ : number → The function returns a number.
🔹 Function with Optional Parameters
Use ? to make parameters optional.
function greet(name: string, age?: number): string {
if (age) {
return `Hello, ${name}. You are ${age} years old.`;
}
return `Hello, ${name}.`;
}
console.log(greet("John")); // Output: Hello, John.
console.log(greet("John", 25)); // Output: Hello, John. You are 25 years old.
4️⃣ TypeScript Interfaces
An interface defines the structure of an object.
🔹 Defining and Using Interfaces
interface Person {
name: string;
age: number;
isStudent?: boolean; // Optional property
}
let user: Person = { name: "Alice", age: 22 };
console.log(user.name); // Output: Alice
✅ Why Use Interfaces?
✔ Ensures objects follow a specific structure.
✔ Helps in better code organization and error prevention.
5️⃣ TypeScript Classes
Classes in TypeScript use object-oriented programming (OOP) principles like encapsulation, inheritance, and polymorphism.
🔹 Defining a Class
class Car {
brand: string;
model: string;
constructor(brand: string, model: string) {
this.brand = brand;
this.model = model;
}
getDetails(): string {
return `Car: ${this.brand} ${this.model}`;
}
}
let myCar = new Car("Toyota", "Corolla");
console.log(myCar.getDetails()); // Output: Car: Toyota Corolla
✅ Key Features:
✔ constructor() initializes object properties.
✔ getDetails() is a method that returns car details.
6️⃣ TypeScript Arrays and Tuples
Arrays and tuples store multiple values.
🔹 Array Declaration
let fruits: string[] = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Output: Apple
🔹 Tuple Declaration
Tuples allow fixed types at specific positions.
let person: [string, number] = ["Alice", 25];
console.log(person[0]); // Output: Alice
✅ Difference:
✔ Array → Stores multiple values of the same type.
✔ Tuple → Stores different types in a specific order.
7️⃣ TypeScript Enums
Enums are used to define a set of named constants.
enum Direction {
Up = 1,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move); // Output: 1
✅ Enums help in better readability when dealing with fixed values.
8️⃣ TypeScript Union and Intersection Types
Union (|) allows multiple types, and Intersection (&) combines types.
🔹 Union Type (Variable can hold multiple types)
let id: number | string;
id = 101; // Valid
id = "AB101"; // Also valid
🔹 Intersection Type (Combining Interfaces)
interface A {
propA: string;
}
interface B {
propB: number;
}
type Combined = A & B;
let obj: Combined = { propA: "Hello", propB: 100 };
✅ Why Use These?
✔ Union types allow flexibility.
✔ Intersection types combine multiple interfaces for more control.
9️⃣ TypeScript Type Aliases
Aliases provide custom names for complex types.
type ID = number | string;
let userId: ID = 123; // Valid
userId = "ABC"; // Also valid
✅ Aliases make code more readable and reusable.
🔟 TypeScript Generics
Generics allow reusable code without specifying exact data types.
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("Hello")); // Output: Hello
console.log(identity<number>(100)); // Output: 100
✅ Generics improve code reusability by allowing different data types.