TS: any, unknown, never, undefined - paulip114/blog GitHub Wiki

๐Ÿง  When to Use unknown, any, never, and undefined in TypeScript

Type Description When to Use
any Bypasses type checking completely Avoid when possible. Use when migrating JS to TS or working with 3rd-party code where types are unclear.
unknown Similar to any but forces type-checking before use Use when you're accepting input (e.g., from user, API, JSON) and want to validate it before using.
never Represents values that should never occur Use for functions that throw or switch cases that should be impossible (e.g., exhaustive enums).
undefined A value that hasnโ€™t been assigned Use for optional parameters or values that may not exist (e.g., foo?: string).

๐Ÿ” 1. any โ€“ Disable TypeScript

let value: any = 'hello'
value.toFixed() // TS doesn't complain, but this will crash!

โœ… Use only if you're dealing with dynamic data and you want to opt out of type safety.


๐Ÿ” 2. unknown โ€“ Safer than any

let input: unknown = getUserInput()
if (typeof input === 'string') {
  console.log(input.toUpperCase()) // โœ… Safe to use
}

โœ… Use unknown when accepting external data (e.g., JSON.parse, user input) and want to force validation before use.


๐Ÿ” 3. never โ€“ Should never happen

function fail(): never {
  throw new Error('This always throws')
}

function exhaustiveCheck(x: never) {} // used in exhaustive switch

โœ… Use never for:

  • Functions that never return
  • Exhaustive switch checks (e.g., all enum values handled)

๐Ÿ” 4. undefined โ€“ A value not set

let user: { name: string, age?: number }

โœ… Use when:

  • A property or argument might not be provided
  • You want to allow intentional absence

๐Ÿงช Summary Table

Type Safe? Typical Use Case
any โŒ Disable type checking
unknown โœ… External input validation
never โœ… Throwing functions, exhaustive switches
undefined โœ… Optional values, return type when no value