TypeScriptBasic types

any

The type that turns off checking: the value can be anything.

On this page

Example

#
TypeScript
let data: any = 'Emma'
data = 42
data = { level: 7 }

console.log(data.level)
console.log(data.name)
Result
7
undefined

Definition and usage

#

The any type tells the compiler: “don’t check this.” You can assign anything to a variable like that, call any method on it, and pass it anywhere. Errors only show up once the program is running.

It can be useful while gradually migrating a project from JavaScript, or with libraries that have no types. In new code, though, it’s a trapdoor that takes away most of the benefits of TypeScript.

When you genuinely don’t know a value’s type, for example data from outside, unknown is a better choice. It forces you to check the type before using it.

Syntax

#
Syntax
let value: any

More examples

#
An error the compiler won’t catch
TypeScript
const response: any = { user: null }

try {
  console.log(response.user.name)
} catch (error) {
  console.log('Runtime error')
}
Result
Runtime error

Good practices

#
  • Turn on the noImplicitAny option, so the compiler doesn’t silently accept any wherever you don’t give a type.
  • Instead of any for data from outside, use unknown together with type narrowing.

Related entries

#

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