Skip to content

Latest commit

 

History

History
165 lines (119 loc) · 3.32 KB

File metadata and controls

165 lines (119 loc) · 3.32 KB

1. Functions

Functions in TypeScript allow us to define input parameter types and return types. This helps catch errors before runtime.

// Function accepting an object and returning a string
function createUser(user: { name: string; college: string }): string {
  return user.name;
}

// Function returning an object (generic empty object)
function createCourseTest(): {} {
  // The return type `{}` means "any non-null object"
  return {};
}

// Function returning a strongly typed object
function createCourse(course: { name: string; Duration: string }): { name: string; Duration: string } {
  return { name: "React", Duration: "" };
}

// Calling function with an object
let newUser = { name: "Mohan", isPaid: false, college: "Presidency" };
createUser(newUser);

2. Objects

Objects can be described using Type Aliases or Interfaces. Type aliases are reusable type definitions.

// Type Alias
type Point = {
  x: number;
  y: number;
};

function printCoord(pt: Point) {
  console.log("X:", pt.x);
  console.log("Y:", pt.y);
}

printCoord({ x: 100, y: 100 });

Readonly & Optional Properties

type User = {
  readonly _id: string;
  name: string;
  email: string;
  isActive: boolean;
  creditCardDetails?: number; // Optional / nullable
};

let myUser: User = {
  _id: "123",
  name: "H",
  email: "h@h.com",
  isActive: false
};

myUser.email = "updated@email.com"; // ✅ allowed
myUser._id = "value";               // ❌ Error: _id is readonly

Combining Types using &

type CardDate = { cardDate: string };
type CardNumber = { cardNumber: number };

type CardDetails = CardDate & CardNumber;

type CardDetailsWithCVV = CardDate & CardNumber & { cvv: number };

3. Arrays

Arrays should specify the type of elements they hold.

// Empty array with unknown type (not recommended)
const superHeros: [] = [];

// Better: explicitly typed
const superHeros1: string[] = [];
superHeros1.push("Marvel");

const superPower: number[] = [];
superPower.push(100);

// Generic array type option
const heroPower: Array<number> = [];

// Array of objects
type User1 = { name: string; isActive: boolean };
const allUsers: User1[] = [];
allUsers.push({ name: "Mohan", isActive: false });

4. Union Types

Union allows a variable to hold multiple possible types.

let score: number | string;
score = 44;
score = "44"; // Both allowed
type AppUser = { name: string; _id: number };
type AppAdmin = { userName: string; id: number };

type MyUser = AppUser | AppAdmin;

let u1: MyUser = { _id: 1, name: "A" };
let u2: MyUser = { id: 1, userName: "Admin" };

Narrowing Union Types

Before performing type-specific actions, check the type.

function getDbId(id: number | string) {
  if (typeof id === "string") id.toLowerCase();
}

Union Arrays

const data: number[] = [1, 2, 3];
const data2: string[] = ["1", "2", "3"];
const data3: (number | string)[] = [1, "2", 3];

Literal Types

Literal types restrict allowed values.

let pi: 3.14 = 3.14;
pi = 1; // ❌ Error

let seatAllotment: "Aisle" | "Middle" | "Window";
seatAllotment = "Aisle";
seatAllotment = "Crew"; // ❌ Not allowed

If you'd like, I can now convert this into a neat PDF cheat sheet — ready to print or reference. Just say: "Make PDF" 🎯