Learn TypeScript

Understanding the any type

Understanding the any type

We met the any type briefly in the last module. In this lesson, we learn more about what this type is and when we would use it.

An example

Let's explore the any type in the code editor.

TypeScriptOpen exercise in CodeSandbox
🤔

What type has the something variable been inferred as?

  • Try assigning different values to something:
something = "Bob";
something = 33;
something = false;
something = new Date(2019, 5, 8);
🤔

Do any type errors occur?

TypeScript doesn't carry out any type checking on items that have the any type. The any type is a way of opting out of the type checking process.

Why would we use the any type?

One of the main reasons for using TypeScript is to enable type checking. So, why does the any type exist, and are there any use cases for using it? Well, when it isn't possible to create a TypeScript type to represent an item, we can use the any type. Historically, when TypeScripts type system wasn't as powerful, this would be the case every so often. However, today, this case rarely happens.

An example where we may see any being used is where we are dealing with dynamic data. This is data that is defined by end-users rather than developers. The ability for end-users to create custom forms is an example of where code would need to deal with dynamic data. The code snippet below is an example of how we could type a custom form's values:

const formValues: { [field: string]: any } = {
firstName: "Bob",
surname: "Smith",
age: 30,
};

We haven't covered the syntax shown in the type annotation yet, so don't worry if it looks scary! The type { [field: string]: any } means an object whose property names are of type string, with property values of type any.

What about when consuming a 3rd party library or a 3rd party web API that hasn't got types? Perhaps we should use any in these cases? Well, even in these cases, there is an approach we can use to strongly-type this code. We'll learn about this when we learn about the unknown type later in this module.

Summary

The main takeaway from this lesson is that no type checking occurs on code that uses the any type. We rarely need to use any today because TypeScript’s type system is so flexible.

Further information about the any type can be found in the TypeScript handbook.

In the next lesson, we’ll learn about the void type.

Did you find this lesson useful?

Share this lesson on twitter
© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more