Technology • 2024-09-10
TypeScript for Beginners: Complete Guide with Examples
Learn TypeScript from scratch — types, interfaces, classes, generics, and why TypeScript makes JavaScript development better.
TypeScriptJavaScriptProgrammingTechnology
⏱ 1 min read
What Is TypeScript and Why Use It?
TypeScript is JavaScript with static types — developed by Microsoft, open source. It catches errors at compile time (before running code), making large codebases maintainable. Used by Google, Microsoft, Airbnb, and most large React/Angular/Node.js projects. TypeScript compiles down to regular JavaScript.
Installation and Setup
npm install -g typescript
tsc --version
# Initialize TypeScript config
tsc --init # creates tsconfig.json
# Compile TypeScript to JavaScript
tsc app.ts # creates app.js
Basic Types
// Primitive types
let name: string = "Ravi";
let age: number = 25;
let isActive: boolean = true;
// Arrays
let fruits: string[] = ["mango", "banana"];
let numbers: Array<number> = [1, 2, 3];
// Tuple
let person: [string, number] = ["Priya", 30];
// Any (avoid when possible)
let data: any = "could be anything";
// Union types
let id: string | number = 42;
id = "ABC123"; // also valid
Interfaces
interface User {
id: number;
name: string;
email: string;
age?: number; // optional field
}
function greetUser(user: User): string {
return `Hello, ${user.name}!`;
}
const user: User = { id: 1, name: "Amit", email: "amit@example.com" };
console.log(greetUser(user));
Classes in TypeScript
class BankAccount {
private balance: number;
readonly accountNumber: string;
constructor(accountNumber: string, initialBalance: number) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
deposit(amount: number): void {
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount("ACC001", 10000);
account.deposit(5000);
console.log(account.getBalance()); // 15000
Generics
function getFirst<T>(arr: T[]): T {
return arr[0];
}
console.log(getFirst([1, 2, 3])); // number
console.log(getFirst(["a", "b", "c"])); // string
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
TypeScript with React
interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
}
const Button: React.FC<ButtonProps> = ({ label, onClick, disabled }) => (
<button onClick={onClick} disabled={disabled}>{label}</button>
);