What Is any Type in TypeScript?

By Hemanta Sundaray on 2023-04-13

If you declare a variable without assigning it an initial value, TypeScript will consider the variable to be of type any. And if a variable is of type any, you can assign it values of different types and TypeScript won’t complain.

Example:

let myName

myName = "hemanta"

myName = true

Here:

  • We first declared a variable named myName without assigning it an initial value.
  • Then, we assigned myName the value hemanta, a string data type.
  • Finally, we reassigned myName the value true, a boolean data type.

Surprisingly, TypeScript didn’t raise any errors, even though there was a change in the data type, from string to boolean. Why? That’s because TypeScript considered the myName variable to be of type any as we declared it without an initial value.

Remember: The main benefit of TypeScript is type checking. However, by using type any, we lose that benefit. Therefore, as a best practice, avoid using any as much as possible.

Join the Newsletter