TypeScriptBasic types
unknown
The safe counterpart to any: a value of an unknown type that you must check before use.
Example
#TypeScript
function describe(value: unknown): string {
if (typeof value === 'string') return `A string of length ${value.length}`
if (typeof value === 'number') return `A number ${value.toFixed(1)}`
if (Array.isArray(value)) return `An array with ${value.length} elements`
return 'Something else'
}
console.log(describe('CodeWorlds'))
console.log(describe(3.14159))
console.log(describe([1, 2, 3]))Result
A string of length 10 A number 3.1 An array with 3 elements
Definition and usage
#The unknown type means a value about which nothing is known. Just like with any, you can assign anything to it, but you can’t use it until you check what it actually is.
You check it by narrowing: typeof value === "string", Array.isArray(value), value instanceof Date, or your own type guard functions. After a check like that, the compiler already knows the exact type inside that block.
It’s the ideal type for data from outside: an API response, the result of JSON.parse(), a value from localStorage, or the error in a catch block.
Syntax
#Syntax
let value: unknownMore examples
#TypeScript
const input: unknown = JSON.parse('{"level": 7}')
console.log(input.level)
// Error: 'input' is of type 'unknown'.Good practices
#- Assign the result of
JSON.parse()tounknown, then check the shape of the data. That protects you from surprises when an API changes. - In
catch (error), the error has the typeunknown. Checkerror instanceof Errorbefore you readerror.message.
Related entries
#- any vs unknownany turns off type checking and allows anything, while unknown also accepts any value but requires a type check before you can use it.
- anyThe type that turns off checking: the value can be anything.
- neverThe type of a value that never occurs: functions that don’t end normally, and impossible cases.
Spotted a mistake or missing an example? Write to us.