Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

TypeScript any vs unknown vs never vs void: When to Use Each

Why does code using any compile but later throw a TypeError? Why can a void callback return something at runtime, and where does never come from? These four types solve different problems. Choosing the right one keeps unchecked assumptions from leaking into application code.

Published Written by Reading time 7 min read
On this page Contents: quick navigation between sections

any vs unknown: why does the compiler miss the error?

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

function safeUppercase(value: unknown): string | undefined {
  if (typeof value !== "string") {
    return undefined;
  }

  return value.toUpperCase();
}

try {
  unsafeUppercase(42);
} catch (error: unknown) {
  console.log(error instanceof TypeError); // true
}

console.log(safeUppercase(42)); // undefined
console.log(safeUppercase("hello")); // HELLO

any allows a method call without knowing that the method exists. The first function compiles even for a number, but fails at runtime. unknown accepts the same input while requiring a typeof check before using string methods. [1][2]

Explicit any can help when migrating a legacy dependency, but isolate it inside an adapter. Do not replace known types with unknown: a precise contract provides more useful guarantees.

How do you safely process API data?

interface Product {
  id: string;
  priceCents: number;
}

function parseProduct(value: unknown): Product {
  if (
    typeof value !== "object" ||
    value === null ||
    !("id" in value) ||
    !("priceCents" in value)
  ) {
    throw new Error("Invalid product");
  }

  const { id, priceCents } = value;

  if (
    typeof id !== "string" ||
    id.trim().length === 0 ||
    typeof priceCents !== "number" ||
    !Number.isSafeInteger(priceCents) ||
    priceCents < 0
  ) {
    throw new Error("Invalid product fields");
  }

  return { id, priceCents };
}

const payload: unknown = JSON.parse(
  '{"id":"p1","priceCents":1299}',
);

const product = parseProduct(payload);

console.log(product.priceCents); // 1299

The standard TypeScript declaration of JSON.parse() returns any. Assigning it to unknown prevents that type from spreading. An assertion such as as Product performs no runtime check. This parser rejects null, missing fields, empty IDs and prices that are not nonnegative safe integers. [1][3]

Construct a new object containing only the accepted fields. For HTTP requests, check the response status and pass the decoded body to the parser; a generic response type is not runtime validation.

Why is a catch variable unknown?

function getErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }

  if (typeof error === "string") {
    return error;
  }

  return "Unexpected error";
}

function parseSettings(text: string): unknown {
  try {
    const settings: unknown = JSON.parse(text);

    return settings;
  } catch (error: unknown) {
    console.error(getErrorMessage(error));

    throw error;
  }
}

console.log(getErrorMessage(new Error("Offline"))); // Offline
console.log(getErrorMessage("Timeout")); // Timeout
console.log(getErrorMessage(null)); // Unexpected error

JavaScript can throw strings, numbers and null as well as Error objects. Accessing .message unconditionally may cause another exception. useUnknownInCatchVariables, enabled by default with strict, requires you to narrow the value first. [5]

The example extracts a diagnostic message and rethrows the original failure instead of reporting success. In a production UI, keep user-facing messages separate from internal diagnostic details.

How does never enforce exhaustive switches?

type RequestState =
  | { status: "loading" }
  | { status: "success"; count: number }
  | { status: "error"; message: string };

function assertNever(value: never): never {
  throw new Error(`Unhandled state: ${String(value)}`);
}

function getStatusText(state: RequestState): string {
  switch (state.status) {
    case "loading":
      return "Loading";

    case "success":
      return `${state.count} results`;

    case "error":
      return state.message;

    default:
      return assertNever(state);
  }
}

console.log(getStatusText({ status: "success", count: 0 })); // 0 results

never has no possible values. After all variants of a discriminated union have been handled, the remaining branch narrows to never. Add a cancelled variant without updating the switch and assertNever(state) becomes a compile-time error. [3][4]

The assertion helper also throws at runtime rather than returning a value. It does not replace validation of external input: construct the union from validated data before relying on exhaustiveness.

Does void really mean no return value?

type OnSaved = (id: string) => void;

const savedIds: string[] = [];

const onSaved: OnSaved = (id) => savedIds.push(id);

function notifySaved(id: string, callback: OnSaved): void {
  callback(id);
}

function getMissingValue(): undefined {
  return undefined;
}

notifySaved("p1", onSaved);

console.log(savedIds); // ["p1"]
console.log(getMissingValue()); // undefined

A callback typed (id: string) => void can be implemented by a function returning the new array length from push(). The caller cannot rely on that result. This differs from explicitly annotating the implementation with : void, which disallows returning a number. [4][10]

undefined is a particular value, not a contract to ignore results. With strictNullChecks, null and undefined are distinct. Use undefined as the return type when that specific value is required. [7]

Why can Promise<void> cause an unhandled rejection?

type SaveDraft = () => Promise<void>;
type ReportError = (error: unknown) => void;

function createSaveHandler(
  saveDraft: SaveDraft,
  reportError: ReportError,
): () => void {
  return () => {
    void saveDraft().catch((error: unknown) => {
      reportError(error);
    });
  };
}

async function saveDraft(): Promise<void> {
  throw new Error("Offline");
}

const handleSave = createSaveHandler(saveDraft, (error) => {
  console.error(error instanceof Error ? error.message : "Save failed");
});

handleSave(); // Offline (asynchronously)

Many () => void callback positions accept async functions, but the caller may not await their Promise. A rejection may then go unhandled. The JavaScript void operator discards the expression value; it does not handle rejection. [8][9]

The synchronous adapter below starts the Promise and handles rejection. It assumes saveDraft returns a Promise and the reporter does not throw. If the caller must wait for completion, use () => Promise<void> and await it explicitly.

Where does never[] come from, and which compiler settings help?

interface CartItem {
  id: string;
  quantity: number;
}

interface CartState {
  items: CartItem[];
}

const cart: CartState = { items: [] };

cart.items.push({ id: "p1", quantity: 2 });

type PossibleStatus = "ready" | never;
type ExternalValue = string | unknown;

const currentStatus: PossibleStatus = "ready";
const externalValue: ExternalValue = 42;

console.log(cart.items.length); // 1
console.log(currentStatus); // ready
console.log(externalValue); // 42

An empty array property without a contextual type can become never[] under strict settings. Annotating CartState provides the intended element type. In unions, never disappears and unknown absorbs string, illustrating the difference between an empty set of values and a type accepting all values. [2][3]

Enable strict and avoid disabling noImplicitAny just to make incomplete code compile. This option does not prohibit explicit any; typed lint rules can enforce additional restrictions. [6][7]

Use a concrete type when the contract is known and unknown at untrusted boundaries. Use never for impossible cases and void for callbacks whose results are not part of the contract. This makes the compiler enforce application invariants rather than silence mismatches.

TypeScript any unknown never void Type Narrowing Type Safety Runtime Validation Exhaustiveness Checking Promise Strict Mode

Frequently asked questions

Is unknown safer than any?

Yes. It requires narrowing before use, but does not validate the value automatically. [2][3]

When should I use never instead of void?

Use never for impossible cases or functions that cannot return normally. A void function can finish normally. [4]

Does as unknown as T validate input?

No. Assertions are erased at compilation and perform no runtime validation. [1]

Does void promise handle errors?

No. Handle rejection with await and try/catch or .catch(). [9]

Sources and references

  1. TypeScript Handbook: Everyday Types↩1↩2↩3↩4↩5
  2. TypeScript 3.0: unknown↩1↩2↩3↩4
  3. TypeScript Handbook: Narrowing↩1↩2↩3↩4↩5↩6
  4. TypeScript Handbook: More on Functions↩1↩2↩3↩4
  5. TSConfig: useUnknownInCatchVariables↩
  6. TSConfig: noImplicitAny↩
  7. TSConfig: strictNullChecks↩1↩2
  8. typescript-eslint: no-misused-promises↩1↩2
  9. typescript-eslint: no-floating-promises↩1↩2↩3
  10. TypeScript Handbook: Type Compatibility↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning