TypeScript Basics
πΉ What is TypeScript?
TypeScript is a strongly typed, object-oriented, and compiled superset of JavaScript developed by Microsoft. It enhances JavaScript by adding static typing, interfaces, and better tooling support, making it ideal for large-scale applications.
β¨ Why Use TypeScript?
β
Type Safety β Catches errors at compile time, reducing runtime issues.
β
Improved Readability & Maintainability β Makes large codebases easier to manage.
β
Supports Modern JavaScript Features β Fully supports ES6+ features.
β
Better IDE Support β Provides better IntelliSense and autocompletion.
πΉ Installing TypeScript
To install TypeScript globally, use npm (Node Package Manager):
npm install -g typescript
To check the installation:
tsc --version
You can compile a TypeScript file (.ts
) into JavaScript (.js
) using:
tsc filename.ts
πΉ Variables and Type Annotations
Unlike JavaScript, TypeScript allows defining types explicitly:
let name: string = "Alice"; // String typelet age: number = 30; // Number typelet isActive: boolean = true; // Boolean type
Type Inference
TypeScript can infer types automatically:
let city = "New York"; // Automatically inferred as a string
πΉ Basic Data Types in TypeScript
TypeScript includes all JavaScript types, plus additional types:
Type | Example |
---|---|
String | "Hello, TypeScript" |
Number | 42 , 3.14 |
Boolean | true , false |
Array | [1, 2, 3] or Array<number> |
Tuple | [string, number] β ["Alice", 25] |
Enum | enum Color { Red, Green, Blue } |
Any | let data: any = "Hello"; |
Void | function logMessage(): void {} |
Never | function throwError(): never { throw new Error("Error"); } |
Example usage of different types:
let names: string[] = ["Alice", "Bob", "Charlie"];let user: [string, number] = ["Alice", 25]; // Tupleenum Color { Red, Green, Blue };let favoriteColor: Color = Color.Green;
πΉ Functions in TypeScript
Functions in TypeScript allow type annotations for parameters and return values:
function add(a: number, b: number): number { return a + b;}console.log(add(5, 3)); // Output: 8
Arrow Functions (ES6 Style)
const multiply = (a: number, b: number): number => a * b;
Optional & Default Parameters
function greet(name: string, age?: number) { return `Hello, ${name}!`;}console.log(greet("Alice")); // Output: Hello, Alice!
πΉ Interfaces in TypeScript
Interfaces define the structure of an object:
interface User { name: string; age: number; isAdmin?: boolean; // Optional property}
let user: User = { name: "Alice", age: 30 };
Interfaces can also be used with functions:
interface MathOperation { (a: number, b: number): number;}
const sum: MathOperation = (x, y) => x + y;
πΉ Classes in TypeScript
TypeScript supports OOP principles like classes, inheritance, and access modifiers:
class Person { private name: string; // Private property protected age: number; // Accessible in derived classes public city: string; // Public property
constructor(name: string, age: number, city: string) { this.name = name; this.age = age; this.city = city; }
getDetails(): string { return `${this.name} is ${this.age} years old from ${this.city}.`; }}
let person = new Person("Alice", 30, "New York");console.log(person.getDetails());
Class Inheritance
typescript class Employee extends Person { constructor(name: string, age: number, city: string, public position: string) { super(name, age, city); } }
let employee = new Employee(βBobβ, 28, βSan Franciscoβ, βDeveloperβ); console.log(employee.getDetails()); πΉ TypeScript and the DOM Manipulating the DOM with TypeScript is similar to JavaScript but with strict type checking:
const button = document.getElementById("btn") as HTMLButtonElement;button.addEventListener("click", () => { alert("Button Clicked!");});
πΉ Generics in TypeScript
Generics allow creating flexible and reusable components:
function identity<T>(value: T): T { return value;}
console.log(identity<number>(42)); // Output: 42console.log(identity<string>("Hello")); // Output: Hello
πΉ TypeScript vs JavaScript
Feature | TypeScript | JavaScript |
---|---|---|
Typing | Static (Strong) | Dynamic (Weak) |
Error Detection | Compile-time | Runtime |
Interfaces | Yes | No |
OOP Support | Advanced | Limited |
Compilation | Requires tsc | Runs directly in browsers |
πΉ Setting Up a TypeScript Project
1οΈβ£ Initialize a project
npm init -ynpm install typescript --save-devnpx tsc --init
2οΈβ£ Create a TypeScript file (index.ts)
const message: string = "Hello, TypeScript!";console.log(message);
3οΈβ£ Compile TypeScript to JavaScript
tsc index.ts
4οΈβ£ Run JavaScript output
node index.js
πΉ Conclusion
TypeScript enhances JavaScript by adding static typing, interfaces, classes, and advanced OOP features. It is widely used for frontend frameworks (Angular, React) and backend development (Node.js, NestJS).
π Next Steps? Explore TypeScript with React, Node.js, or Angular!