TypeScript is a superset of JavaScript that adds static typing.
Purpose: Catch errors early and improve code maintainability.
let isDone: boolean = false;
let age: number = 25;
let username: string = "John";
let scores: number[] = [90, 80];
let data: any = "anything";
Purpose: Declare types explicitly to avoid errors.
let city = "New York"; // inferred as string
Purpose: Let TypeScript guess the type based on assignment.
function add(a: number, b: number): number {
return a + b;
}
Purpose: Type input and return values for clarity.
type ID = number | string;
let userId: ID = "abc";
Purpose: Name a union or complex type for reuse.
interface User {
id: number;
name: string;
}
Purpose: Define a contract for object shapes.
let value: string | number;
type A = { a: number };
type B = { b: string };
type AB = A & B;
Purpose: Combine or separate possible types.
enum Direction { Up, Down, Left, Right }
let dir = Direction.Up;
Purpose: Use readable names for constants.
function identity(arg: T): T {
return arg;
}
Purpose: Create reusable and type-safe functions/components.
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase());
}
}
Purpose: Safely use a value after checking its type.
let someValue: any = "hello";
let length = (someValue as string).length;
Purpose: Tell TS a more specific type when you know better.
class Person {
constructor(public name: string) {}
greet() {
console.log(`Hi, I'm ${this.name}`);
}
}
Purpose: Write OOP-style code with reusable logic.
class Car {
private speed: number;
protected model: string;
public brand: string;
}
Purpose: Control access to class members.
abstract class Shape {
abstract area(): number;
}
Purpose: Enforce implementation of abstract methods in subclasses.
Partial
Required
Readonly
Pick
Omit
Purpose: Modify existing types with built-in helpers.
type IsString = T extends string ? true : false;
Purpose: Create types that depend on conditions.
// math.ts
export function add(x: number, y: number): number { return x + y; }
// app.ts
import { add } from './math';
Purpose: Organize code across multiple files.
type Keys = keyof User;
type Book = Record;
let val: never = (() => { throw "error" })();
Purpose: Leverage TS power tools for advanced control.