unknown Type
- Represents any value, but is safer than
any—you cannot use its value directly without type-checking or type assertion - Use when you want to accept any type but enforce type-safety downstream
Example:
function logValue(value: unknown) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
Key Points:
- Forces you to perform a type check before using the value
- Useful in libraries for handling user input, JSON parsing, etc.
never Type
- Represents values that never occur
- Used as the return type for functions that never return (e.g., throw exceptions or have infinite loops)
Example:
function fail(message: string): never {
throw new Error(message);
}
Key Points:
- Helpful for exhaustive checks (e.g., switch statements)
- Informs TypeScript that code after a
neverfunction is unreachable
When to Use Which?
- Use
unknownfor any value you want type-checked later - Use
neverfor impossible states or functions never meant to return
Top comments (0)