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 anybut 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 switchchecks (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 |