any vs unknown

View saved

Why any is risky

any turns off checking. You can call anything on it and mistakes slip through.

function bad(value: any) {
  return value.toUpperCase();
}

// Compiles, then crashes at runtime if value is a number:
// bad(42);

Prefer unknown

unknown is safer: you must narrow before using the value.

function show(value: unknown) {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  } else {
    console.log("Not a string");
  }
}

show("hello");
show(10);

Type assertions carefully

Assertions tell the compiler to trust you. Prefer narrowing when possible.

const raw: unknown = JSON.parse('{"n":1}');
const data = raw as { n: number };
console.log(data.n);

When any still appears

  • Legacy JavaScript migration may use temporary any
  • Third-party packages without types sometimes force escapes
  • Replace any with interfaces as you learn the shape
  • Enable noImplicitAny in tsconfig so missing types are visible

Comments

One comment per signed-in account. Comments are saved with this page’s URL.