What does the 'unknown' type represent, and how is it safer than 'any'?
Short answer
'unknown' represents a value whose type isn't known yet — like 'any', it can hold ANY value, but unlike 'any', you CANNOT perform any operations on an 'unknown' value (property access, calling it, arithmetic) until you first narrow it to a more specific type via a type guard…
Advertisement
AModel answer
'unknown' represents a value whose type isn't known yet — like 'any', it can hold ANY value, but unlike 'any', you CANNOT perform any operations on an 'unknown' value (property access, calling it, arithmetic) until you first narrow it to a more specific type via a type guard, ensuring you can't accidentally misuse it.
function processInput(input: unknown) {
// input.toUpperCase(); // Error: 'input' is of type 'unknown'
if (typeof input === 'string') {
console.log(input.toUpperCase()); // OK, narrowed to string
}
}Real-world example
Typing a value from an untrusted source (JSON.parse result, external API response) as 'unknown' to force safe narrowing before use.
Likely follow-ups
- Why is 'unknown' generally recommended over 'any' for function parameters accepting external/uncertain data?
Related topics