TypeScriptBasic types

unknown

The safe counterpart to any: a value of an unknown type that you must check before use.

On this page

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: unknown

More examples

#
No use without a check
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() to unknown, then check the shape of the data. That protects you from surprises when an API changes.
  • In catch (error), the error has the type unknown. Check error instanceof Error before you read error.message.

Related entries

#

Spotted a mistake or missing an example? Write to us.