TypeScript Introduction
Understanding TypeScript fundamentals
📘 What is TypeScript?
TypeScript is a superset of JavaScript developed by Microsoft that adds static type definitions. It compiles to plain JavaScript and helps developers catch errors during development, making code more reliable and easier to maintain.
// TypeScript adds types to JavaScript
let username: string = "Alice";
let age: number = 25;
let isActive: boolean = true;
Core TypeScript Features
Type Annotations
Explicitly declare variable types
let count: number = 10;
let name: string = "John";
Type Inference
TypeScript infers types automatically
let message = "Hello"; // string
let total = 100; // number
Interfaces
Define object shapes
interface User {
id: number;
name: string;
}
Functions
Type parameters and return values
function add(a: number, b: number): number {
return a + b;
}
🔹 Basic Types
TypeScript provides several basic types for common values:
// String
let firstName: string = "John";
// Number
let age: number = 30;
// Boolean
let isStudent: boolean = false;
// Array
let numbers: number[] = [1, 2, 3, 4, 5];
let names: Array<string> = ["Alice", "Bob"];
// Tuple
let person: [string, number] = ["John", 30];
// Any (avoid when possible)
let data: any = "could be anything";
// Void (for functions that don't return)
function logMessage(msg: string): void {
console.log(msg);
}
🔹 Interfaces and Types
Define custom types for objects:
🔸 Interface
interface Product {
id: number;
name: string;
price: number;
inStock?: boolean; // Optional property
}
const laptop: Product = {
id: 1,
name: "MacBook Pro",
price: 1999
};
🔸 Type Alias
type Point = {
x: number;
y: number;
};
const coordinate: Point = { x: 10, y: 20 };
// Union types
type Status = "pending" | "approved" | "rejected";
let orderStatus: Status = "pending";
🔹 Functions in TypeScript
Add types to function parameters and return values:
// Function with typed parameters and return type
function multiply(a: number, b: number): number {
return a * b;
}
// Arrow function
const divide = (a: number, b: number): number => {
return a / b;
};
// Optional parameters
function greet(name: string, greeting?: string): string {
return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`;
}
// Default parameters
function createUser(name: string, role: string = "user"): void {
console.log(`${name} is a ${role}`);
}
console.log(multiply(5, 3)); // 15
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob", "Hi")); // Hi, Bob!
🔹 Classes in TypeScript
TypeScript adds type support to JavaScript classes:
class Animal {
name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public makeSound(): void {
console.log(`${this.name} makes a sound`);
}
getAge(): number {
return this.age;
}
}
const dog = new Animal("Buddy", 3);
dog.makeSound(); // Buddy makes a sound
console.log(dog.getAge()); // 3
🔹 Generics
Create reusable components that work with multiple types:
// Generic function
function identity<T>(value: T): T {
return value;
}
let num = identity<number>(42);
let str = identity<string>("Hello");
// Generic interface
interface Box<T> {
content: T;
}
const numberBox: Box<number> = { content: 123 };
const stringBox: Box<string> = { content: "TypeScript" };
🔹 Type Assertions
Tell TypeScript the specific type of a value:
// Using 'as' syntax
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
// Using angle-bracket syntax
let anotherValue: any = "another string";
let anotherLength: number = (<string>anotherValue).length;
console.log(strLength); // 16
console.log(anotherLength); // 14