#typescript #beginner #types

Day 7: The Any, Unknown, and Never Types

The Good, The Bad, and The Safe

Welcome to Day 7! This marks the end of Phase 1. Today we look at three special types that often confuse beginners.

1. any (The Bad)

any turns off TypeScript checking for that variable. It’s an escape hatch.

let vague: any = 4;
vague = "string"; // OK
vague = false; // OK
vague.methodThatDoesNotExist(); // OK (Runtime Error!)

Avoid any. It silences the compiler. Only use it when you are migrating old Javascript code and can’t fix types yet.

2. unknown (The Safe)

unknown is the type-safe counterpart to any. It says: “I don’t know what this is yet, so I won’t let you use it until you check.”

let input: unknown = 4;
// let num: number = input; // Error! Type 'unknown' is not assignable to 'number'.

if (typeof input === "number") {
  let num: number = input; // OK, we checked.
}

Use unknown for API responses where you aren’t sure of the shape yet.

3. never (The Impossible)

never represents values that never occur. It’s often used for functions that throw errors or infinite loops.

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

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

It’s also used in advanced type guards to ensure all cases are handled.

Phase 1 Wrap-Up

Congratulations! You’ve completed the Foundation Phase. You now know:

  • How to set up TS.
  • Primitives (string, number, boolean).
  • Arrays and Tuples.
  • Objects, Types, and Interfaces.
  • Functions.
  • Special types.

Coming up in Phase 2 (Day 8-12): Object-Oriented Programming (Classes, Inheritance, Access Modifiers).

Challenge for Today

  1. Write a function that takes an argument of type unknown.
  2. Use typeof checks to handle if it’s a string (log it uppercase) or a number (multiply by 2).
  3. Try to use a method on the variable without checking its type first and see the error.

See you in Phase 2!