Skip to content

no-hidden-any ​

An any nobody wrote: a type of TypeScript's lib or of Node that hands one out. MessageEvent or CustomEvent without a type argument, MessageEvent<Job> (a claim about another context's data), Function, history.state, event.data in a "message" listener whose parameter isn't annotated, Node's workerData and a worker's "message" value. On by default, as an error.

Why: no-any bans the keyword, but lib declares any in places of its own, and an any switches off every check Result, Option and Enum rest on: the value can be read as anything (event.data.user.name), assigned to anything (const user: User = event.data, a cast nobody wrote) and returned as anything. TypeScript says nothing, so neither does a run of tsc. unknown says the same thing, "not checked yet", and makes you check.

❌ Rejected: event.data is any, so the message is believed whatever it holds

✕ Rejectedno-hidden-any
ts
type Progress = { readonly done: number; readonly total: number };

export function percent(event: MessageEvent): number {
  const progress: Progress = event.data;
  return (100 * progress.done) / progress.total;
}

✅ Accepted: the data is unknown until it is checked

✓ Accepted0 diagnostics
ts
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import { q, type Result } from "@evobug_com/safe-ts-std/result";

type Progress = { readonly done: number; readonly total: number };

export function percent(event: MessageEvent<unknown>): Result<number, JsonError> {
  const progress = q(validate<Progress>(event.data));
  return (100 * progress.done) / progress.total;
}
ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result } from "@evobug_com/safe-ts-std/result";

type Progress = { readonly done: number; readonly total: number };

export function percent(event: MessageEvent<unknown>): Result<number, JsonError> {
  const __q1 = __jsonValidate<Progress>(event.data, __v0); if (__q1 instanceof __qErr) return __q1; const progress = __q1;
  return (100 * progress.done) / progress.total;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "done": number; "total": number; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j1 = v["done"];
  if (typeof __j1 !== "number") return __jsonFail(p + ".done", "number", __j1);
  const __j2 = __j1;
  const __j3 = v["total"];
  if (typeof __j3 !== "number") return __jsonFail(p + ".total", "number", __j3);
  const __j4 = __j3;
  const out: { "done": number; "total": number; } = { "done": __j2, "total": __j4 };
  return out;
}

❌ Rejected: the type argument says what a worker posted, and nothing checks it

✕ Rejectedno-hidden-any
ts
type Progress = { readonly done: number; readonly total: number };

export function follow(worker: Worker, signal: AbortSignal): void {
  worker.addEventListener("message", (event: MessageEvent<Progress>) => {
    console.log(event.data.done / event.data.total);
  }, { signal });
}

MessageEvent<Progress> is the cast event.data as Progress, moved into a type argument: the data comes from another context (a worker, another window, a socket), and is whatever that sent. Take MessageEvent<unknown> and validate<T>(event.data), as above. What the platform itself guarantees is fine: MessageEvent<string>, MessageEvent<ArrayBuffer | Blob>, typed arrays. So is CustomEvent<T>: the program dispatches it and receives it, in one realm.

❌ Rejected: an unannotated listener gets a MessageEvent<any>; history.state is any

✕ Rejectedno-hidden-any
ts
export function follow(worker: Worker, signal: AbortSignal): void {
  worker.addEventListener("message", (event) => {
    console.log(event.data.step);
  }, { signal });
}

export function page(): number {
  return history.state.page;
}

✅ Accepted: annotated unknown, then checked

✓ Accepted0 diagnostics
ts
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import { isErr, q, type Result } from "@evobug_com/safe-ts-std/result";

type Step = { readonly step: number };
type Page = { readonly page: number };

export function follow(worker: Worker, signal: AbortSignal): void {
  worker.addEventListener("message", (event: MessageEvent<unknown>) => {
    const message = validate<Step>(event.data);
    if (isErr(message)) console.error("not a step", message.error);
    else console.log(message.step);
  }, { signal });
}

export function page(): Result<number, JsonError> {
  const state = q(validate<Page>(history.state));
  return state.page;
}
ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { isErr, q, type Result } from "@evobug_com/safe-ts-std/result";

type Step = { readonly step: number };
type Page = { readonly page: number };

export function follow(worker: Worker, signal: AbortSignal): void {
  worker.addEventListener("message", (event: MessageEvent<unknown>) => {
    const message = __jsonValidate<Step>(event.data, __v0);
    if (isErr(message)) console.error("not a step", message.error);
    else console.log(message.step);
  }, { signal });
}

export function page(): Result<number, JsonError> {
  const __q1 = __jsonValidate<Page>(history.state, __v1); if (__q1 instanceof __qErr) return __q1; const state = __q1;
  return state.page;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "step": number; };
type __T1 = { "page": number; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j1 = v["step"];
  if (typeof __j1 !== "number") return __jsonFail(p + ".step", "number", __j1);
  const __j2 = __j1;
  const out: { "step": number; } = { "step": __j2 };
  return out;
}
function __v1(v: unknown, p: string): __JsonResult<__T1> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j3 = v["page"];
  if (typeof __j3 !== "number") return __jsonFail(p + ".page", "number", __j3);
  const __j4 = __j3;
  const out: { "page": number; } = { "page": __j4 };
  return out;
}

❌ Rejected: Function can be called with anything and returns any

✕ Rejectedno-hidden-any
ts
export function run(task: Function): string {
  return task().label;
}

✅ Accepted: the signature it has

✓ Accepted0 diagnostics
ts
type Task = () => { readonly label: string };

export function run(task: Task): string {
  return task().label;
}

What it reports ​

  • A type whose argument defaults to any, written without one: MessageEvent (event.data), CustomEvent (event.detail), ReadableStream, ReadableStreamDefaultReader, WritableStream, WritableStreamDefaultWriter, TransformStream and IDBRequest. MessageEvent<unknown> or what the platform delivers (MessageEvent<string>) is fine. A parameter or variable annotated MessageEvent or CustomEvent is reported once it is used: passed on, or its data (detail) read other than into a sink below. One whose data goes straight into const data: unknown = event.data, or that only reads event.origin, isn't. In a signature without a body (a function type, an interface's method), where the type hands the any to whoever implements it, the annotation is always reported.
  • MessageEvent<T> with a T other than unknown, string, ArrayBuffer, Blob, ArrayBufferView, Uint8Array, DataView (or a union of them): a claim about data from another context, which nothing checked.
  • Function, as a type anywhere, and new Function(...), which makes one (unless it goes straight into trust<(a: number) => number>(...), which gives it a signature).
  • A property typed any, read: history.state (also window.history.state); window.opener; a Storage property that isn't one of its methods (localStorage.theme, localStorage[key]: the index); and in an event listener whose parameter isn't annotated (addEventListener("...", (event) => ...) or x.onmessage = (event) => ...), event.data for "message" and "messageerror", event.state for "popstate", event.reason for "unhandledrejection", event.error for "error". The same properties of a value of one of these types, however the code reaches it: a parameter or variable annotated with it, a class field (declared, or assigned in the constructor), an element of a list of them (for ... of, a callback's element, list[0]?.), a const holding one, a getter or a function's declared return type (signalOf().reason, also of another file), await of a promise of one, each also typed Option<T> (std's or the prelude's) or T | undefined (an element of a list of them too), and controller.signal / request.signal (an AbortSignal) of an AbortController or a Request; the whole program finds the type, so a type of the project's own with a field of that name (ticket.reason) is left alone. The types: PopStateEvent, PromiseRejectionEvent, PromiseRejectedResult, ErrorEvent, XMLHttpRequest (response, also of new XMLHttpRequest()), IDBCursorWithValue (value), Notification and ExtendableMessageEvent (data), PropertyDescriptor (value, get: a legacy decorator's descriptor parameter), AbortSignal (reason), AggregateError (errors), SuppressedError (error, suppressed) and Window (opener).
  • Node's node:worker_threads: workerData; the value a "message" listener gets on a Worker, MessagePort or BroadcastChannel of worker_threads, on parentPort, or on a port of its MessageChannel (.on, .once, .addListener, ...), when the parameter isn't annotated; receiveMessageOnPort(port).message. And every unannotated parameter of a listener on an EventEmitter of node:events made or declared without an event map (new EventEmitter(); new EventEmitter<{ ready: [port: number] }>() is typed). A read of workerData.path under a test of typeof workerData.path (in a ?:, an if, or the right of &&) is narrowed by TypeScript, and isn't reported.

Which listeners count. A listener's event goes by the receiver, not only by the event's name: "message" gives a MessageEvent<any> on a DOM event target, and something else on ws's WebSocket (RawData) or on an emitter the project types itself. A listener counts only where the receiver is visibly one of the kinds above: window, self, globalThis, the global addEventListener, navigator.serviceWorker; a parameter, variable or class field declared with one of lib's Worker, BroadcastChannel, WebSocket, EventSource, MessagePort, ServiceWorker, ServiceWorkerContainer or a worker's global scope (or with worker_threads' and node:events' types); one made with new Worker(...), new globalThis.WebSocket(...) and the like; a port of a MessageChannel. A receiver declared with a type the project or a package declares (import { WebSocket } from "ws") isn't one of them, and neither is one whose type the rule can't see (an unannotated parameter, a call's result, this.socket without a declared field): those are left alone. That misses an any behind a receiver of unknown type, and never reports a listener whose event is typed.

A read isn't reported where the any goes no further: into a binding annotated unknown (const state: unknown = history.state), return in a function declared to return unknown, std's validate<T>(...) or trust<T>(...), a parameter declared unknown of a function in the same file, String(...), console.log(...), JSON.stringify(...), history.replaceState(...) / pushState(...), typeof, instanceof, ! and ===. A read handed to a method, or to a function of another file, is reported even where that parameter is declared unknown, which the rule can't see: put the value in a binding annotated unknown first (const data: unknown = event.data), or take the quick fix. Names you declare or import yourself (a MessageEvent type of a library) aren't lib's, and aren't reported.

Quick fixes ​

  • Write MessageEvent<unknown> (and the same for the other types): the type argument.
  • Replace Function with (...args: never[]) => unknown: a function that can be stored and passed on, but not called until its signature is written.
  • Annotate event: MessageEvent<unknown> on a "message" listener's parameter.
  • Write MessageEvent<unknown> in place of a type argument that claims what arrives.
  • Annotate value: unknown on the parameter of a worker_threads "message" listener or of an untyped EventEmitter's listener.

Each changes only types. What then reads the value without checking it is a tsc error, which says where validate<T> goes.

The any that std's strict-lib takes away ​

What a method of lib returns can be retyped, and @evobug_com/safe-ts-std/strict-lib does: JSON.parse, response.json() (and request.json()), Array.isArray (unknown[], or the array members of a union), new Map() / new Set() / new WeakMap() / new WeakSet() without type arguments or entries (their types come from the annotation, else unknown), new Array(n) / Array(n) (the same: const slots: number[] = new Array(n), new Array<number>(n).fill(0)), Object.create(null) ({}: no fields to read until you put them there; const counts: Record<string, number> = Object.create(null) still works) and Object.create(proto) (proto's type), Object.fromEntries of entries that aren't pairs, Object.values / Object.entries of a type without an index (an interface, a class: it may hold more than it lists), Object.getPrototypeOf (object | null), Object.setPrototypeOf (the object given), Object(value) (object), Object.assign of four sources or more (what the first four give, as lib types it for up to three), a property descriptor's value and get() (Object.getOwnPropertyDescriptor(s), Reflect.getOwnPropertyDescriptor), Reflect.get of a key the type doesn't have, Reflect.apply of a target typed only Function, Reflect.construct of a constructor its arguments don't fit (Reflect.construct(Date, [])), the values a JSON.stringify replacer gets, the captures a replace / replaceAll callback gets (a group that didn't take part is undefined), and a promise's rejection reason (.catch((reason) => ...), .then(ok, (reason) => ...), also of a PromiseLike) give unknown. Then tsc refuses the flow, as it refuses value.name on an unknown. Turn it on in tsconfig.json (setup):

jsonc
// tsconfig.json
{ "compilerOptions": { "types": ["@evobug_com/safe-ts-std/strict-lib"] } }

A types list replaces TypeScript's default of loading every @types package: keep the ones you use ("node") and the prelude in it.

Every any of lib, accounted for. A test of the repository (crates/safe_ts_core/tests/lib_any.rs) reads TypeScript's own declarations for the documented setup (ES and DOM, and Node's types) and lists every member that hands code an any: a return type, a property, a parameter of a callback it is given, a type parameter defaulting to any. Of 962 today, strict-lib retypes 26, this rule reports 31, and the other 905 are listed in tests/lib-any/allowed.txt, each with why it is left: an event handler property's => any (what a handler may return), a listener overload for an event name the declarations don't list, toJSON(), an options object the code passes in, Node's members (which strict-lib can't name: it loads without Node's types), WebGL's getters, ... The test fails on a member in none of the three, so a TypeScript or @types/node upgrade that adds one shows up.

safe-ts check warns when the tsconfig that applies doesn't load it. And without it, std's unsafe(() => JSON.parse(text)) and unsafeAsync(() => response.json()) already give Result<unknown, unknown>, as do the feature packs' safe versions (json(response)).

What the rule can't see ​

It reads the code, without a type checker, so the APIs are a curated list, by name:

  • A library's own any: an untyped package, or one whose declarations return any (a .d.ts that says any, an axios call without a type argument). Wrap such a call in unsafe(...), which gives unknown for a function returning any, or give it its type argument, then validate<T>.
  • A value whose type only the type checker knows: event.data after event instanceof MessageEvent (which narrows to MessageEvent<any>), a Function that typeof x === "function" narrows to, the property of a listener's parameter passed in from elsewhere (addEventListener("message", onMessage) with onMessage(event: MessageEvent) is reported at its annotation, though).
  • A receiver of unknown type: this.socket.onmessage = (event) => event.data.x without a declared field, a target returned by a call or passed in unannotated (see "Which listeners count" above).
  • Node's other any: a process's "message" (process.on("message", ...)), require(...), events.once(emitter, name)'s any[], a subclass of EventEmitter and a stream's "data" listener ((chunk: any)). Annotate the parameter unknown.
  • A read through a sink the rule can't see: an any handed to a method, to a function of another file or to a callback typed by its context, where that parameter is declared unknown, is still reported.
  • What strict-lib retypes, when the tsconfig doesn't load it: JSON.parse(text).name and Array.isArray(value) on an unknown compile then; the check's warning says so.
  • A Vue template: {{ history.state.page }} isn't read by this rule (a component's <script> is).
  • Lib's other any: the 905 members of tests/lib-any/allowed.txt, among them a generator's or iterator's return type (next() called by hand on an Iterator<T>: write Iterator<T, undefined>), the bare global opener, structuredClone of an any, a Node stream's chunks (for await (const chunk of readable)), what an IDBObjectStore.get request gives, WebGL's getParameter, and one of the properties above read from a value that isn't shown to have that type: one narrowed by a test (result.reason after result.status === "rejected" on a PromiseSettledResult, error.errors after error instanceof AggregateError), what a lib function returns (AbortSignal.timeout(ms).reason), a package's value (MessageEvent and CustomEvent without a type argument are reported where the type is written, a field's annotation too, not at each read of data / detail through it); a table property called through such a receiver (this.descriptor.get(): a call of a member is a method's, map.get(key), and isn't followed); and a binding declared with a type alias imported from another file that names one of these types (a name declared with a type is judged by the name written).

Related: no-any, the keyword; no-unchecked-cast; guide: JSON.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra