Typescript Foundations / Basic Types

any, unknown, void, never

1️⃣ any

  • Represents any type of value.

  • Disables type checking for that value — TypeScript won’t check or warn about what you do with it.

let value: any = 5;
value = "hello";    // OK
value = true;       // OK
value.toUpperCase(); // No TS error — but might fail at runtime if not a string

⚠ When to use?

  • When migrating JS code to TS gradually

  • When you truly don’t know what type it will be

    💡 But generally avoid any because you lose type safety.


2️⃣ unknown

  • Also represents any value, BUT safer than any

  • You can’t do anything with an unknown value without first checking its type.

let input: unknown = "hello";

input.toUpperCase();   // ❌ Error

if (typeof input === "string") {
  input.toUpperCase(); // ✅ OK after type check
}

⚠ When to use?

  • When accepting input where the type is not known up front (e.g. API input)

  • When you want to force type checking before use


3️⃣ void

  • Represents the absence of a return value in a function.

function logMessage(message: string): void {
  console.log(message);
}

✅ The function returns nothing (undefined implicitly).

⚠ When to use?

  • As a return type for functions that don’t return anything.

💡 A variable of type void can only be assigned undefined (or null if --strictNullChecks is off):

let a: void = undefined;

4️⃣ never

👉 Represents a value that never occurs.

👉 Used for:

  • Functions that throw errors

  • Functions with infinite loops

  • Exhaustiveness checks

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

function infiniteLoop(): never {
  while (true) {}
}

✅ TypeScript knows code after calling such functions is unreachable.

⚠ When to use?

  • Return type of a function that never completes normally

  • Ensuring all cases in switch statements are handled

type Shape = "circle" | "square";

function getArea(shape: Shape): number {
  switch (shape) {
    case "circle": return 3.14;
    case "square": return 4;
    default:
      const _exhaustiveCheck: never = shape;  // Enforces all cases handled
      return _exhaustiveCheck;
  }
}

📝 Summary table

Type

Meaning

Example use

any

Anything, disables type checking

Dynamic or legacy JS values

unknown

Anything, but requires checking before use

Safe external input

void

No value returned

console.log, event handlers

never

Never returns / never happens

Functions that throw, infinite loops