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
- Write a function that takes an argument of type
unknown. - Use
typeofchecks to handle if itâs a string (log it uppercase) or a number (multiply by 2). - Try to use a method on the variable without checking its type first and see the error.
See you in Phase 2!