Menu

Special Types: any, unknown, void, and never

Lesson 4: Special Types: any, unknown, void, and never

What are the special types?

Type Meaning Type-safe? Typical use
any Turns off type checking No Temporary escape hatch during migration
unknown Could be anything; must be checked before use Yes JSON, API responses, catch errors
void Function returns nothing useful Yes Event handlers, logging functions
never A value that can never exist Yes Functions that always throw; exhaustive checks

Example

// any: everything is allowed, even bugs
let risky: any = 'hello';
risky.toFixed(2); // No error, crashes at runtime

// unknown: you must check first
function parseOrder(json: string): unknown {
  return JSON.parse(json);
}

const data = parseOrder('{"id":"o1","total":957}');
data.total;
// Error: 'data' is of type 'unknown'.

if (typeof data === 'object' && data !== null && 'total' in data) {
  console.log(data.total); // OK after checking
}

// void: no meaningful return
function logOrder(id: string): void {
  console.log(`Order ${id} placed`);
}

// never: this function never returns
function fail(message: string): never {
  throw new Error(message);
}

How it works

  • any spreads: anything you get from an any value is also any, so errors disappear silently.
  • unknown is the safe alternative. TypeScript forces you to narrow it (check what it is) before using it. Module 5 covers narrowing in depth, and Module 10 shows how libraries like Zod do it for you.
  • In catch (error), the error is unknown under strict, because anything can be thrown.
  • never is also what TypeScript infers when every possibility has been ruled out, which powers exhaustive checks (Module 5).

Common mistakes

Mistake Effect Fix
Using any to make errors go away Bugs hidden until runtime Use unknown and narrow, or write the correct type
Typing JSON.parse results as the expected type without checking Wrong data trusted Validate at runtime (Module 10)
Returning a value from a void function and relying on it Confusing APIs Return a real type if the value matters

Key takeaways

  • Prefer unknown over any for values you do not know yet.
  • Use void for functions with no meaningful return, and never for impossible values.

Try it: Write a function toNumber(input: unknown): number that returns the number if input is a number, parses it if it is a numeric string, and throws otherwise.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details