Showing posts with label TypeScript. Show all posts
Showing posts with label TypeScript. Show all posts

Oct 25, 2025

TypeScript any vs unknown: Key Differences and Best Practices

Working with dynamic or external data in TypeScript can be tricky especially when you’re not sure what shape that data will take. This is where the any and unknown types come in, each handling uncertainty in a different way. While any acts as a “turn off type safety” switch, letting you do anything without checks, unknown forces you to validate and narrow types before using them.


Understanding the key differences between these two special types will help you write much safer, more predictable, and maintainable TypeScript code, especially when handling API responses or user input.


TypeScript any vs unknown: Key Differences and Best Practices


What is 'any' in TypeScript?


The any type in TypeScript is an “escape hatch” that turns off type checking for a variable. Once you use any, you can assign any value and perform any action on that value, and the compiler won’t catch errors, even deeply unsafe actions. It’s like telling TypeScript, “Trust me, I know what I’m doing!”.

Example:


let value: any = "Hello";
value = 42;
value = { greet: "Hi" };
console.log(value.nonExistentMethod()); // No error at compile time, will crash at runtime!


What is 'unknown' in TypeScript?


The unknown type is a safer alternative to any. Like any, it allows assignment of any value but you can’t perform arbitrary operations on it until you explicitly check or assert its type. TypeScript forces you to prove what the value is before using it.


let result: unknown = "Hello";
if (typeof result === "string") {
  console.log(result.toUpperCase()); // ✅ Safe, type checked
}

Trying to use unknown directly triggers a compile-time error!


Type Narrowing for 'unknown' (typeof, instanceof, custom guards)


Before using an unknown value, narrow its type:

if (typeof input === "string") { /* ... */ }
if (input instanceof Array) { /* ... */ }
function isUser(val: unknown): val is User { return typeof val === "object" && val !== null && "email" in val; }


How TypeScript Treats Type Checking for 'any' vs 'unknown'


  • any: No type checks; compiler lets anything through.
  • unknown: The compiler requires type narrowing or assertion before use, enforcing safety.

Why 'unknown' is Safer than 'any'


'unknown' forces you to check or narrow the type before every operation, reducing runtime bugs. By using 'unknown', you keep TypeScript’s guarantees, making your code easier to debug, refactor, and scale safely.


When to Use 'unknown' Instead of 'any'


Use unknown for external data with unpredictable shape API responses, user input, deserialized JSON, so you’re required to validate before using it.

Example:


function handleApiResponse(data: unknown) {
  if (typeof data === "object" && data !== null && "success" in data) {
    // Safe to proceed!
  }
}


When 'any' Is Necessary (Limiting Scope)


Sometimes any is needed rapid prototyping, using broken external libraries, or testing. Always restrict its usage to small scopes, and migrate to unknown or concrete types quickly.


Common Mistakes Developers Make with 'any'


  • Overusing any leads to silent bugs and runtime crashes.
  • Assigning any too early disables TypeScript for the rest of the code.
  • Using any for APIs, user data, or third-party packages instead of validating types.

Real-World Use Cases for 'unknown'


Check some Real World use cases for type unknown below-

1- Handling API Response Data with 'unknown'


Always type your API responses with unknown first, and check their shape:


function getData(): Promise<unknown> { /* ... */ }
getData().then(response => {
  if (typeof response === "object" && response !== null) { /*...*/ }
});


2- Working with Dynamic User Input Safely Using 'unknown'


If you get dynamic input from forms, treat it as unknown:


function processInput(input: unknown) {
  if (typeof input === "string") { /* ... */ }
}


3- Validating Unknown JSON Data



function validateJSON(val: unknown): val is User {
  return typeof val === "object" && val !== null && "email" in val;
}


Migrating from 'any' to 'unknown': Step-by-Step


  • Change your variable’s type from any to unknown.
  • Add type checks wherever you use that variable.
  • Use custom type guards as needed.
  • Refactor dependent code to ensure strict safety.

TypeScript Best Practices: Avoid 'any', Embrace 'unknown'


  • Default to unknown for untyped data.
  • Only use any for prototyping, legacy code, or unavoidable hacks.
  • Always narrow unknown to concrete types before use.
  • Leverage custom guards for advanced validation.

Summary


The any type gives you total freedom but sacrifices all safety making TypeScript act like plain JavaScript, with all its potential runtime surprises. In contrast, unknown is a safer alternative, allowing you the flexibility to receive any value while ensuring you still leverage TypeScript’s powerful compile-time checks.

By embracing unknown, you push yourself and your team to narrow types and validate assumptions, leading to fewer bugs and more robust applications. Whenever you’re dealing with unpredictable or external data, reach for unknown over any your future code (and coworkers) will thank you.

Oct 24, 2025

Mastering TypeScript Generics: Reusable, Type-Safe, and Scalable Code

If you’ve ever wanted to write reusable TypeScript code that’s both flexible and type-safe, generics are your best friend. Generics allow you to define functions, interfaces, and classes that work with any data type, while still enforcing strict type checking. Imagine writing a utility or hook just once and having TypeScript guarantee it works for strings, numbers, objects, or even complex structures, with no loss of type safety. 


Whether you’re building simple libraries or scalable app architectures, understanding generics will help you avoid repetitive code, catch more bugs at compile time, and keep your codebase clean and robust.


typescript-generics


What are Generics in TypeScript?


Generics are a powerful TypeScript feature that lets you create reusable, type-safe code without specifying concrete types up front. They act as placeholders (like <T>) for types that are filled in later, so your functions, classes, and interfaces can work with any data type and still maintain full type safety.


Example (generic function):


function identity<T>(value: T): T {
  return value;
}

const num = identity<number>(42);    // num is type number
const str = identity<string>("Hello"); // str is type string


Why Do We Use Generics in TypeScript?


Generics make code more flexible and reusable, while preserving static type checking. Instead of duplicating similar logic for multiple types, you can write one generic function/class/interface that works with them all.


  • Prevent runtime type errors by catching mistakes at compile-time
  • Write utility code once; reuse for different data structures
  • Reduce code duplication


How Generics Improve Type Safety and Reusability


With generics, TypeScript tracks what type is used, “locking in” the type at the usage site but leaving implementation flexible. This lets you catch type mismatches early and build solid, reusable utilities.


Example (interface):


interface Pair<T, K> {
  first: T;
  second: K;
}
const pair: Pair<string, number> = { first: "one", second: 2 };


When to Use Generics in Functions, Interfaces, and Classes


  • Functions: For utilities that operate on any type
  • Interfaces/Types: For data structures that hold variable types
  • Classes: For things like collections, repositories, or state containers


Example (class):


class Box<T> {
  constructor(private value: T) {}
  getValue(): T { return this.value; }
}
const numberBox = new Box<number>(42);


Difference Between Generics and any Type


Generics (<T>)
any
Placeholder for a specific type
Accepts any type, loses safety
Checked by TypeScript at compile time
Not checked (no autocomplete)
Preserves type information
Results in type loss, potential errors

  • Use generics for type safety and flexibility; avoid any unless you need to bypass checks deliberately.


Generic React Components and Props (<T> with React.FC)


TypeScript generics help make truly flexible React components:


type ListProps<T> = { items: T[]; renderItem: (item: T) => JSX.Element };

function List<T>({ items, renderItem }: ListProps<T>) {
  return <ul>{items.map(renderItem)}</ul>;
}


Creating Reusable Utility Hooks with Generics (e.g., useFetch<T>)


Generics are perfect for scalable React hooks:


function useFetch<T>(url: string): T | null {
  // fetch and parse data as type T
}

const user = useFetch<User>("/api/user"); // infers User type
const posts = useFetch<Post[]>("/api/posts"); // infers Post[]


Implementing Repository Patterns with Generics (Repository<T>)


You can keep your data access code DRY with generic repositories:


class Repository<T> {
  private items: T[] = [];
  add(item: T) { this.items.push(item); }
  findAll(): T[] { return this.items; }
}

const userRepo = new Repository<User>();
const postRepo = new Repository<Post>();
userRepo.add({ id: 1, name: "Alice" });


Debugging Common TypeScript Generic Errors


  • Implicit any: TypeScript may infer "any" if the generic type can’t be determined. Always provide explicit types if possible.
  • Type constraints: Use "extends" for generic bounds: function logLength<T extends { length: number }>(val: T) {...}
  • Mismatched types: Check your assignments carefully; type mismatches show up at compile-time.

How Generics Are Used in Popular Libraries

  • React Query: types queries with generics: useQuery<T>()
  • Redux Toolkit: infers slice state with generics
  • Prisma: returns typed results for any model defined in the schema
  • Axios: passes response types with generics: axios.get<T>()
Generics power much of TypeScript’s ecosystem, enabling autocomplete, error checking, and more.

Performance and Maintainability Benefits of Generics


Performance: TypeScript generics don’t impact runtime speed; they only exist at compile time for safety.
Maintainability: Drastically reduce code duplication. Generic logic is clearer and easier to update. When you change the underlying type or data model, usage updates across the codebase are triggered thanks to the type system.


Summary


Generics in TypeScript make it possible to write one set of logic that adapts to any type, ensuring both reusability and strong type safety. They’re used everywhere: in array utilities, React hooks, repositories, and popular libraries like Axios and React Query.


By mastering generics, you not only prevent subtle type errors but also boost maintainability and performance across your projects. Whether you’re handling simple lists or crafting advanced patterns, generics give your code the flexibility and reliability it needs to scale confidently.

Sep 22, 2025

Type vs Interface in TypeScript: Clear Differences and When to Use Each

TypeScript's interface vs type debate cost my team 3 weeks of refactoring during a massive API migration. We had 200+ data models scattered across type User = and interface User {} declarations. TypeScript compiler was happy, but VS Code IntelliSense choked, half our types couldn't extend third-party libraries, and junior devs spent 6 hours each googling "why can't I extend this type?"

That painful audit forced me to create team-wide rules that eliminated 97% of these debates forever. Let me share the exact scenarios, production gotchas, and decision framework I use across 25+ TypeScript projects.

type-vs-interface-typescript

The API migration nightmare that created my rules


The Problem: Migrating from REST to GraphQL meant rewriting 347 data models:
  • 87 User variants (AdminUser, CustomerUser, GuestUser)
  • 124 Order types (OrderSummary, DetailedOrder, AdminOrder)
  • 93 Product schemas (CatalogProduct, CartProduct, ReviewProduct)
  • 43 Response wrappers (ApiResponse<T>, Paginated<T>)

What broke immediately:

1. Types couldn't merge with third-party GraphQL codegen 2. VS Code "Go to Definition" failed 43% of the time 3. Junior devs couldn't extend existing models 4. Union types became impossible with interfaces

The fix took 3 weeks because no one had consistent rules.

Rule #1: Interfaces for object shapes that teams extend

Scenario: User management system shared across 8 teams.

Interfaces win because of declaration merging:

// team-auth.ts
interface User {
  id: string;
  email: string;
  role: 'user' | 'admin';
}

// team-profile.ts  
interface User {  // Merges automatically!
  profile: {
    firstName: string;
    lastName: string;
    avatarUrl?: string;
  };
}

// team-analytics.ts
interface User {  // Merges again!
  lastSeen: Date;
  totalOrders: number;
}


Final shape (magic!):

interface User {
  id: string;
  email: string;
  role: 'user' | 'admin';
  profile: { firstName: string; lastName: string; avatarUrl?: string };
  lastSeen: Date;
  totalOrders: number;
}
Types FAIL here:

// BROKEN - Can't merge
type User = { id: string; email: string };
type User = { profile: {...} };  // Duplicate identifier error!


Rule #2: Types for complex compositions (unions, intersections)

Scenario: Order processing pipeline with 7 different states.

Types dominate:

// All possible order states
type OrderStatus = 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled';

// Complex API response shapes
type ApiResponse<T< = 
  | { success: true; data: T }
  | { success: false; error: string };

// Combining multiple shapes
type DetailedOrder = BasicOrder & {
  customer: User;
  shippingAddress: Address;
  paymentMethod: PaymentMethod;
};

// Tuple for batch operations
type BatchResult = [success: boolean, id: string, error?: string][];


Interfaces struggle:

// Ugly - no clean unions
type OrderStatus = 'pending' | '...'  // Interface can't do this

// Verbose intersections
interface DetailedOrder extends BasicOrder {
  customer: User;
  // ... 20 more lines
}


Rule #3: Interfaces for React props/components (always)

Why: Props evolve, teams extend, declaration merging FTW.

// components/UserCard/UserCard.tsx
interface UserCardProps {
  user: User;
  onEdit?: () => void;
}

// components/UserCard/UserCardWithAvatar.tsx
interface UserCardProps {  // Merges!
  showAvatar?: boolean;
  avatarSize?: 'small' | 'medium' | 'large';
}

// Usage anywhere
function UserCard({ user, onEdit, showAvatar }: UserCardProps) {
  // Perfect IntelliSense everywhere
}
VS Code result: Go to Definition works across 15 files instantly.

Production decision matrix (print this)


OBJECT SHAPE + TEAM COLLABORATION? ├── Public APIs → interface ✅✅✅ ├── React props → interface ✅✅✅ ├── Third-party extension → interface ✅✅✅ └── Declaration merging needed → interface ✅✅✅ COMPLEX COMPOSITIONS? ├── Unions → type ✅✅✅ ├── Intersections → type ✅✅✅ ├── Primitives → type ✅✅✅ ├── Tuples → type ✅✅✅ ├── Complex aliases → type ✅✅✅ MIXED NEEDS? └── Start with interface, convert to type if unions needed


Real refactoring examples (before → after)


BEFORE (inconsistent chaos):

// file1.ts
type User = { id: string; name: string };

// file2.ts  
interface UserResponse {
  data: User;
  meta: { total: number };
}

// file3.ts
type ApiResult<T> = T | { error: string };


AFTER (consistent rules):

// models.ts
export interface User {
  id: string;
  name: string;
}

export interface UserResponse {
  data: User;
  meta: { total: number; page: number };
}

export type ApiResult<T> = 
  | { success: true; data: T }
  | { success: false; error: string };


Benefits:
  • VS Code IntelliSense: 43% → 98% success rate
  • Extension conflicts: 23 → 0
  • Junior dev questions: 14/week → 1/week
  • Refactor time: 3 weeks → 2 days (next project)

Advanced patterns from 25+ production apps


1. Hybrid approach (best of both):

// Core shape (interface)
interface Product {
  id: string;
  name: string;
  price: number;
}

// Complex variants (type)
type ProductWithStock = Product & {
  stockQuantity: number;
  lowStockThreshold: number;
};

type ProductSummary = Pick<Product, 'id' | 'name'>;
type ProductDetail = Product & {
  description: string;
  reviews: Review[];
};


2. Declaration merging with third-parties:

// Augment Apollo Client types
declare global {
  interface Window {
    __APOLLO_DEVTOOLS__: any;
  }
}

// Extend Express Request
declare module 'express-serve-static-core' {
  interface Request {
    currentUser?: User;
  }
}


3. Mapped types (types win):

// Convert readonly → mutable
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

// Partial but keep required IDs
type PartialExceptId<T extends { id: any }> = {
  readonly id: T['id'];
} & Partial<Omit<T, 'id'>>;


Team linting rules (enforce consistency)

  
{
  "extends": ["@typescript-eslint/recommended"],
  "rules": {
    "@typescript-eslint/consistent-type-definitions": ["error", "interface"], 
    "@typescript-eslint/prefer-interface-type": "warn"
  }
}


Results: Zero debates. Compiler enforces my rules.

Common mistakes I made (and fixed)


Mistake 1: Everything as interface

// BROKEN
interface StringAlias = string;  // Syntax error!
interface UserOrGuest = User | Guest;  // No unions!


Mistake 2: Everything as type

// BROKEN - Can't extend third-party types
type ExpressRequest = OriginalRequest & { user: User };  // No merging!


Mistake 3: Inconsistent props

// File 1
interface ButtonProps { onClick: () => void; }

// File 2  
type ButtonProps = { onClick: () => void };  // IntelliSense breaks!


Complete production example: E-commerce domain



// Interfaces: Core domain models
export interface Product {
  id: string;
  name: string;
  price: number;
  categoryId: string;
}

export interface Category {
  id: string;
  name: string;
  parentId?: string;
}

// Types: Complex operations
export type CartItem = Product & {
  quantity: number;
  addedAt: Date;
};

export type OrderStatus = 
  | 'pending' 
  | 'confirmed' 
  | 'shipped' 
  | 'delivered' 
  | 'cancelled';

export type ApiResponse<T> = 
  | { success: true; data: T }
  | { success: false; error: string; code?: number };

// Props: React components
export interface ProductCardProps {
  product: Product;
  onAddToCart?: (productId: string) => void;
  showPrice?: boolean;
}


Conclusion: My 3-word rule


OBJECTS → interface COMPLEXITY → type CONSISTENT → team wins

Interfaces = collaboration + extensibility
Types = flexibility + composition

Don't debate. Follow the matrix above. Your VS Code will thank you, your team will love you, and refactoring becomes trivial.

Difference between Interface and Type

Feature TypeScript Interface TypeScript Type
Purpose Defines shape of objects/classes Defines objects, primitives, unions, intersections
Extensibility Supports declaration merging & extends keyword Can create intersections (&) but no declaration merging
Primitive Types Can’t describe primitives Can alias primitives like string, number, boolean
Union / Intersection Supports extending but no union/intersection types Supports union ( | ) and intersection ( & ) types
Use Case Best for public APIs & extensible object shapes Best for flexible type aliases, complex compositions

Real-Time Scenario: Defining User Profiles


Imagine you’re building a social app with user profiles.

Using Interface:

Here, interfaces let you extend UserProfile seamlessly, useful when APIs evolve or third-party types need augmentation.

Using Type:

Types allow you to combine multiple shapes using intersections, great for complex data structures involving unions or tuples.


When to Choose Which?


Choose Interface: When designing public APIs or object models that might need extension or merging.

Choose Type: For more complex type compositions like unions, tuples, or primitives where flexibility is needed.

Pro tip: Run git grep -c "type \|interface" across your codebase. If ratio > 3:1 either way, audit immediately.

Jan 28, 2023

What is a Nullish coalescing operator '??'

Have you ever logged a value, expected 0, and instead seen your “default” kick in and silently change the result? That was the exact moment the nullish coalescing operator ?? clicked for many JavaScript developers: it gives you defaults only when a value is truly missing, not just falsy like 0 or " ".

Why ?? solved a real bug for me


On one project, there was a pagination component where currentPage could legitimately be 0 for the first page. The code looked innocent:


const page = currentPage || 1;


Most of the time it worked—but whenever currentPage was 0, the expression treated it as “no value” and silently switched to 1. Users kept getting redirected to page 1 even though the API clearly returned 0. That bug cost a surprisingly long debugging session.

The fix was one tiny change:


const page = currentPage ?? 1;


Suddenly, 0 stayed 0. Only null or undefined triggered the default. That was the day ?? went from “new operator” to “must‑have tool” in the mental toolbox for many developers.


nullish-coalescing-operator-js


What the nullish coalescing operator actually does


The nullish coalescing operator ?? looks just like || at a glance, but the rule it follows is different:


  • value ?? fallback
- returns value if value is not null or undefined
- otherwise returns fallback

In other words:
  • Treat only null and undefined as “missing”
  • Keep 0, false, " ", and NaN as valid values

This makes it ideal when you want to distinguish between “not provided at all” and “provided, but falsy on purpose”.


Quick comparison: || vs ??


Consider this table of behaviors for the same value and different operators:


// Logical OR
console.log(0 || 10);          // 10
console.log("" || "default");  // "default"
console.log(false || true);    // true
console.log(null || "fallback"); // "fallback"
console.log(undefined || "fallback"); // "fallback"

// Nullish coalescing
console.log(0 ?? 10);          // 0
console.log("" ?? "default");  // ""
console.log(false ?? true);    // false
console.log(null ?? "fallback"); // "fallback"
console.log(undefined ?? "fallback"); // "fallback"


So the mental shortcut is:
  • Use || when you consider all falsy values as “empty” and want a default for them.
  • Use ?? when 0, " ", and false are legitimate values you want to preserve.​

Everyday use cases where ?? shines


1. Setting default values without breaking 0 or " "


Imagine a user preferences object:


const settings = {
  theme: "dark",
  itemsPerPage: 0,        // 0 means "show all"
  nickname: "",           // empty string is allowed
};


If you write:


const itemsPerPage = settings.itemsPerPage || 10;
const nickname = settings.nickname || "Guest";


you accidentally overwrite legitimate values:
  • itemsPerPage becomes 10 instead of 0
  • nickname becomes "Guest" instead of ""

With ??:


const itemsPerPage = settings.itemsPerPage ?? 10; // stays 0
const nickname = settings.nickname ?? "Guest";    // stays ""


The defaults now only apply if the property is missing or explicitly null.

2. Optional function arguments


Sometimes you want to allow callers to deliberately pass 0 or false as values while still having a default when they omit the argument:


function createTimer(delayMs) {
  const delay = delayMs ?? 1000; // default only if undefined/null
  console.log(`Timer delay: ${delay}ms`);
}

createTimer();      // 1000
createTimer(0);     // 0 (allowed)
createTimer(null);  // 1000


This avoids the common trap of using delayMs || 1000, which would treat 0 as “no delay”.

3. Configuration and environment variables


In configuration files or environment variables, it is common to have explicit false or 0 values. Using ?? lets configuration stay in control:


const config = {
  logLevel: 0,          // 0 = only errors
  enableCache: false,   // explicitly disabled
};

const logLevel = config.logLevel ?? 2;      // 0 is respected
const enableCache = config.enableCache ?? true; // false is respected


Only if logLevel or enableCache are missing or null will the defaults kick in.

4. Dealing with messy API data


APIs sometimes return null when data is not present. ?? helps you convert those to sane defaults while still honoring valid zero‑like values:


const user = {
  name: "Jay",
  age: null,    // unknown age
  score: 0,     // score 0 is valid
};

const age = user.age ?? "N/A";      // "N/A"
const score = user.score ?? 100;    // 0 (kept)


If the backend later starts sending undefined instead of null, the same logic still works because ?? treats both as “missing”.

5. Combining with optional chaining


The combination of optional chaining ?. and ?? is extremely useful for deep data structures:


const city = user.profile?.address?.city ?? "Unknown";


This single line says:
  • If user.profile or address is missing, do not crash—just yield undefined.
  • If the final city is null or undefined, default to "Unknown".
  • But if city is an empty string, keep it as is.

This pattern is perfect when dealing with deeply nested API responses or form data where some branches might not exist.

When should you actually reach for '??' ?


A simple rule of thumb:
  • If your domain treats 0, false, or "" as valid user choices → prefer ??.
  • If you really mean “anything falsy should fall back” → || is fine.

After using ?? for a while, it becomes the default choice for configuration, user input, component props, and any place where “missing” is different from “intentionally empty”.