Special Types: Any, Unknown, and Never
TypeScript introduces a few specialized types designed specifically to help control and restrict flexible variables.
1. The any Type
The any type completely disables Type-Checking for that specific variable. It behaves identically to standard, unsafe Vanilla JavaScript.
let suspiciousData: any = "Hello";
suspiciousData = 42; // Works
suspiciousData = true; // Works
// Will crash at runtime, but TS compiler ignores it!
suspiciousData.toUpperCase();
Warning: Avoid using
anyat all costs. Usinganydefeats the entire purpose of having TypeScript compiled into your project.
2. The unknown Type
unknown is the safer alternative to any. It signifies that we don't know the type of the value currently, but before we process it or run methods on it, TypeScript will FORCE us to manually check the type.
let mysteriousData: unknown = 100;
// TS Error: 'mysteriousData' is of type 'unknown'.
let mathCalculation = mysteriousData + 50;
// Valid approach using Type Narrowing!
if (typeof mysteriousData === "number") {
let result = mysteriousData + 50; // Suddenly works!
}
3. The never Type
never represents a value that will literally never occur. It is commonly used as a return type for functions that infinitely loop or inevitably throw giant systemic crash errors.
// This function will never reach an endpoint or return gracefully.
function crashSystem(message: string): never {
throw new Error(message);
}
4. The void Type
Unlike never, a function returning void perfectly finishes executing safely. It's simply used to imply the function completes but returns nothing (like null or undefined).
function sayHello(): void {
console.log("Just running a log, nothing to return here.");
}