TypeScriptBasic types
any
The type that turns off checking: the value can be anything.
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: anyMore examples
#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
noImplicitAnyoption, so the compiler doesn’t silently acceptanywherever you don’t give a type. - Instead of
anyfor data from outside, useunknowntogether with type narrowing.
Related entries
#Spotted a mistake or missing an example? Write to us.