Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

How to Use the `any` Type in TypeScript—and When to Avoid It

TypeScript’s any opts out of type checking. Learn when it can help, why unknown is safer for uncertain values, and how to catch inferred any.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use TypeScript’s any only when you deliberately need to opt out of type checking—for example, as a temporary bridge during a JavaScript migration or when working with code whose types are unavailable. If a value’s shape is simply unknown, start with unknown and narrow it before using it. Enable noImplicitAny or strict to catch inferred any; neither setting bans explicit any annotations.

What any does

A value typed any can be assigned to other types and used with arbitrary property access, function calls, and operations without the compiler checking whether they are valid. Values derived from it can also become any, allowing the unchecked type to spread through your code.

As an Amazon Associate I earn from qualifying purchases.

For example, this compiles even though the parsed object’s count property is a string rather than a number:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function readExternalValue(): any {
  return JSON.parse('{"count":"not a number"}');
}

const count: number = readExternalValue();

The assignment is accepted because any opts out of the relevant check; it does not establish that the runtime value is a number. TypeScript’s Handbook describes any as a way to work with existing JavaScript while opting in or out of type checking during compilation.

Type annotations are erased at runtime. They do not validate JSON or other external input. If your program needs to trust a value from outside the type-checked code, validate it at runtime before relying on its shape.

Choose between any, unknown, and noImplicitAny

Situation Better starting point Reason
The value’s type is not known yet unknown It can hold any value, but must be narrowed before use as a specific type.
The value is passed through without being inspected unknown, in most cases It represents uncertainty without permitting unchecked operations.
A JavaScript migration needs a temporary bridge Explicit, narrowly scoped any It can help migration proceed, but that location has no type safety and should be revisited.
The compiler infers any because it lacks enough information noImplicitAny or strict These settings report inferred any; they do not prohibit explicit annotations.
A callback’s return value is intentionally ignored void TypeScript’s Do’s and Don’ts recommends void rather than any for this case.

Why unknown is safer for uncertain values

unknown lets you hold a value without claiming to know its type. Before using it as a number, string, or other specific type, first perform a check that narrows it. For example:

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
function readExternalValue(): unknown {
  return JSON.parse('{"count":3}');
}

const value = readExternalValue();

if (typeof value === "number") {
  // value is narrowed to number here.
}

This illustrates narrowing, not complete JSON validation: the example returns an object, so the number check does not establish that the object has a numeric count property. Validate the actual structure your program expects.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why noImplicitAny is not a ban on any

noImplicitAny tells the compiler to report places where it would otherwise infer any. A developer can still explicitly write : any. The TSConfig reference documents the option; the broader strict family enables it along with other strict checks.

To enable the broader set in tsconfig.json:

{
  "compilerOptions": {
    "strict": true
  }
}

You can enable noImplicitAny directly instead if you want that inference check without turning on the full strict family. If your team also wants to discourage explicit any, establish a separate linting or code-review policy; compiler configuration alone does not do that.

When using any is reasonable

  • Gradual JavaScript migration: use it as temporary scaffolding where modeling a value would otherwise block conversion. Keep each use narrow and replace it as the value becomes better understood. TypeScript’s migration guidance discusses adopting stricter checks during conversion and acknowledges that any locations lack type safety.
  • Unavailable type information: a third-party library or existing JavaScript code may not provide usable types. The Handbook describes any as an option when type information is unavailable or an annotation would take inappropriate effort. Prefer a narrow boundary over letting it spread through unrelated code.
  • Deliberately unchecked interoperation: if you intentionally need to interact with a value without TypeScript checking those operations, any provides that escape hatch. Make the loss of checking explicit rather than treating it as an ordinary default.

How to reduce any during a migration

  1. Turn on noImplicitAny or strict. This exposes places where the compiler inferred any because it lacked information.
  2. Keep explicit migration annotations localized. Use any only at points where conversion needs a temporary bridge, rather than returning it from broadly used functions or passing it through many layers.
  3. Replace each annotation as the value becomes understood. Give known values appropriate types; use unknown when the value is still uncertain and narrow it before operations that depend on its shape.
  4. Revisit remaining explicit uses. Compiler settings catch inference problems, not explicit annotations, so review those annotations through code review or a separate linting policy.

The declaration-file guidance advises avoiding any except during migration and using unknown when a type is not known or a value will pass through without interaction.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle caught errors as unknown

JavaScript permits throwing values of any type, so a caught value is not guaranteed to be an Error. TypeScript 4.4 added useUnknownInCatchVariables, which makes catch variables default to unknown; enabling strict includes this option. Narrow the value before reading properties such as message:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
try {
  runTask();
} catch (error) {
  if (error instanceof Error) {
    console.error(error.message);
  }
}

The TypeScript 4.4 release notes document the option and demonstrate narrowing with instanceof Error.

Further reading

For broader TypeScript guidance, O’Reilly lists a second edition of Effective TypeScript, updated for TypeScript 5 and including advice on limiting any. It is optional reading; the TypeScript Handbook links above address the specific language behavior discussed here.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.