TS (TypeScript) is a strongly-typed superset of JavaScript developed by Microsoft. It adds optional static typing, modern JavaScript features, and tooling to enhance code quality and maintainability. TypeScript compiles to plain JavaScript and is widely used for large-scale applications.
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 42]; // Fixed-type array
enum Color { Red = "RED", Green = "GREEN" }; // Enumerations
let notSure: any = "could be anything"; // Opt-out of type-checking
let nothing: void = undefined; // Common for function returns
Define object shapes:
interface User {
id: number;
name: string;
email?: string; // Optional property
}
const user: User = { id: 1, name: "Alice" };
Type annotations for parameters and return values:
function add(a: number, b: number): number {
return a + b;
}
// Optional/default parameters
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
class Person {
private age: number; // Access modifiers: public, private, protected
constructor(public name: string, age: number) {
this.age = age;
}
// Method
describe(): string {
return `${this.name} is ${this.age} years old.`;
}
}
// Inheritance
class Employee extends Person {
constructor(name: string, age: number, public role: string) {
super(name, age);
}
}
Reusable code with type variables:
function identity<T>(arg: T): T {
return arg;
}
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
}
const response: ApiResponse<User> = { data: user, status: 200 };
type StringOrNumber = string | number; // Union
type Combined = User & { permissions: string[] }; // Intersection
Check types at runtime:
if (typeof value === "string") { /* ... */ }
if (value instanceof User) { /* ... */ }
- Type Aliases:
type Point = { x: number; y: number };
- Utility Types:
Partial<T>
: All properties optional.Pick<T, K extends keyof T>
: Select subset of properties.Record<K, T>
: Map a type to keys.Readonly<T>
: Immutable properties.
Compile TypeScript to JavaScript:
tsc file.ts # Generates file.js
Use a tsconfig.json
for project settings:
{
"compilerOptions": {
"target": "ES6",
"strict": true
}
}
interface Product {
id: number;
name: string;
price: number;
}
class Cart {
private items: Product[] = [];
addItem(item: Product): void {
this.items.push(item);
}
total(): number {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}
const cart = new Cart();
cart.addItem({ id: 1, name: "Laptop", price: 999 });
console.log(cart.total()); // 999