TS Advanced Types

TypeScript Advanced Types

TypeScript provides powerful ways to combine and manipulate types for complex scenarios.

Advanced types allow you to model intricate business logic with absolute precision.

These tools ensure data integrity across highly dynamic web applications.

Mastering them separates junior developers from senior software engineers.


1. Intersection Types

Intersection types allow you to combine multiple types into one single unified type.

You create them using the ampersand symbol (&) between existing types or interfaces.

An object of an intersection type must contain all properties from all merged types.

This is incredibly useful for combining mixins and extending structural shapes safely.

Intersection Example:

type Admin = { privileges: string[] };
type Employee = { name: string; startDate: Date };

// ElevatedUser must have both name, startDate, AND privileges type ElevatedUser = Admin & Employee;

const manager: ElevatedUser = { name: "Akash", startDate: new Date(), privileges: ["CREATE_SERVER"] };

console.log("Manager Name:", manager.name);


2. Discriminated Unions

Discriminated unions are a pattern used to safely work with complex state management.

They rely on a common literal property (a "discriminator") present across multiple types.

By checking this property, TypeScript automatically narrows down the exact type for you.

This pattern is heavily utilized in state reducers like Redux and React's useReducer.

Discriminated Union Example:

interface Square { kind: "square"; size: number; }
interface Rectangle { kind: "rectangle"; width: number; height: number; }

type Shape = Square | Rectangle;

function getArea(shape: Shape) { // TypeScript knows 'shape' is a Square here because of 'kind' if (shape.kind === "square") { return shape.size * shape.size; } return shape.width * shape.height; }

console.log("Area is:", getArea({ kind: "square", size: 5 }));


3. SEO and Type Predictability

Using advanced types guarantees your application state is 100% predictable at compile time.

Predictable state drastically reduces runtime exceptions that frustrate website visitors.

Lower bounce rates directly translate to much stronger search engine rankings.

Robust typing also allows code minifiers to optimize bundles much more aggressively.

Type Aliasing Complexity:

type NetworkLoadingState = { state: "loading" };
type NetworkFailedState = { state: "failed"; code: number };
type NetworkSuccessState = { state: "success"; response: object };

type NetworkState = NetworkLoadingState | NetworkFailedState | NetworkSuccessState;


Exercise

?

Which symbol is used to create an Intersection Type?


4. Final Thoughts

Advanced types provide the structural cement needed for complex enterprise software.

They help define exact possibilities, preventing impossible states from compiling.

Next, we will learn how to safely narrow these types down using Type Guards!