TS: any, unknown, never, undefined - paulip114/blog GitHub Wiki
unknown
, any
, never
, and undefined
in TypeScript
๐ง When to Use 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 ). |
any
โ Disable TypeScript
๐ 1. 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.
unknown
โ Safer than any
๐ 2. 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.
never
โ Should never happen
๐ 3. 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)
undefined
โ A value not set
๐ 4. 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 |