TypeScript Advanced Types

TypeScript tutorial

🚀 TypeScript Advanced Types (Complete Guide)

Advanced Types in TypeScript help you write safer, more expressive, and scalable code.
They are heavily used in real-world apps (React, Node.js) and are common in interviews.


1️⃣ Union Types (|) ⭐

Allow a variable to be one of multiple types.

let id: number | string;

id = 101;
id = “A101”;

Union in Functions

function printId(id: number | string) {
console.log(id);
}

2️⃣ Intersection Types (&) ⭐

Combine multiple types into one.

type Person = { name: string };
type Employee = { empId: number };
type Staff = Person & Employee;const s: Staff = {
name: “Rahul”,
empId: 123
};

✔ Must satisfy all types


3️⃣ Type Aliases 🔖

Create a custom name for a type.

type ID = number | string;

let userId: ID;

✔ Improves readability
✔ Reusable


4️⃣ Literal Types ⭐

Restrict values to specific literals.

let status: "success" | "error" | "loading";

status = “success”; // ✅
// status = “done”; ❌

✔ Very common in APIs & UI state


5️⃣ Type Narrowing 🔍 (Very Important)

TypeScript narrows types using checks.

typeof

function add(a: number | string, b: number | string) {
if (typeof a === "number" && typeof b === "number") {
return a + b;
}
return a.toString() + b.toString();
}

in Operator

type Admin = { role: "admin"; permissions: string[] };
type User = { role: "user"; email: string };
function check(u: Admin | User) {
if (“permissions” in u) {
console.log(“Admin”);
}
}

6️⃣ Discriminated (Tagged) Unions ⭐⭐

A powerful pattern using a common property.

type Circle = {
kind: "circle";
radius: number;
};
type Rectangle = {
kind: “rectangle”;
width: number;
height: number;
};type Shape = Circle | Rectangle;

function area(shape: Shape) {
switch (shape.kind) {
case “circle”:
return Math.PI * shape.radius ** 2;
case “rectangle”:
return shape.width * shape.height;
}
}

✔ Extremely common in React reducers


7️⃣ unknown vs any

any ❌ (Avoid)

let x: any;
x.foo.bar(); // no error, dangerous

unknown ✅ (Safe)

let x: unknown;

if (typeof x === “string”) {
console.log(x.toUpperCase());
}

✔ Forces type checking


8️⃣ never Type 🔥

Represents values that never occur.

function throwError(msg: string): never {
throw new Error(msg);
}

Exhaustiveness Check

function assertNever(x: never): never {
throw new Error("Unexpected value");
}

✔ Used in advanced safety checks


9️⃣ Optional & Nullable Types ❓

type User = {
name: string;
age?: number; // optional
};
let email: string | null;

🔟 Type Assertions (as) ⚠️

Tell TypeScript you know better.

let value: unknown = "Hello";

let len = (value as string).length;

⚠️ No runtime checking


1️⃣1️⃣ Mapped Types 🔁

Create new types from existing ones.

type ReadOnlyUser<T> = {
readonly [K in keyof T]: T[K];
};
type User = { name: string; age: number };type ReadOnly = ReadOnlyUser<User>;


1️⃣2️⃣ Conditional Types ⭐⭐

Types based on conditions.

type IsString<T> = T extends string ? true : false;

type A = IsString<string>; // true
type B = IsString<number>; // false


1️⃣3️⃣ Utility Types (Very Important) ⭐⭐⭐

Built-in helpers:

type User = {
id: number;
name: string;
age: number;
};
UtilityExample
Partial<T>All optional
Required<T>All required
Readonly<T>Immutable
Pick<T, K>Select keys
Omit<T, K>Remove keys
Record<K, T>Key-value map
type UserPreview = Pick<User, "id" | "name">;

1️⃣4️⃣ Index Signatures 🔑

type ErrorMap = {
[key: string]: string;
};
const errors: ErrorMap = {
email: “Invalid”,
password: “Too short”
};

1️⃣5️⃣ Advanced Function Types

type MathOp = (a: number, b: number) => number;

const add: MathOp = (x, y) => x + y;


❌ Common Mistakes

  • Overusing any

  • Forgetting type narrowing

  • Ignoring never

  • Misusing type assertions

  • Not using discriminated unions


📌 Interview Questions (Must Prepare)

  1. Difference between type and interface

  2. any vs unknown

  3. What is a discriminated union?

  4. What is never used for?

  5. Union vs Intersection types

  6. Utility types examples


✅ Summary

✔ Advanced types improve type safety & scalability
✔ Unions & intersections model real data
✔ Discriminated unions are extremely powerful
✔ Utility & conditional types reduce boilerplate
✔ Essential for React, Node.js & interviews

You may also like...