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,TransformStreamandIDBRequest.MessageEvent<unknown>or what the platform delivers (MessageEvent<string>) is fine. A parameter or variable annotatedMessageEventorCustomEventis reported once it is used: passed on, or itsdata(detail) read other than into a sink below. One whosedatagoes straight intoconst data: unknown = event.data, or that only readsevent.origin, isn't. In a signature without a body (a function type, an interface's method), where the type hands theanyto whoever implements it, the annotation is always reported. MessageEvent<T>with aTother thanunknown,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, andnew Function(...), which makes one (unless it goes straight intotrust<(a: number) => number>(...), which gives it a signature).- A property typed
any, read:history.state(alsowindow.history.state);window.opener; aStorageproperty 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) => ...)orx.onmessage = (event) => ...),event.datafor"message"and"messageerror",event.statefor"popstate",event.reasonfor"unhandledrejection",event.errorfor"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]?.), aconstholding one, a getter or a function's declared return type (signalOf().reason, also of another file),awaitof a promise of one, each also typedOption<T>(std's or the prelude's) orT | undefined(an element of a list of them too), andcontroller.signal/request.signal(anAbortSignal) of anAbortControlleror aRequest; 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 ofnew XMLHttpRequest()),IDBCursorWithValue(value),NotificationandExtendableMessageEvent(data),PropertyDescriptor(value,get: a legacy decorator's descriptor parameter),AbortSignal(reason),AggregateError(errors),SuppressedError(error,suppressed) andWindow(opener). - Node's
node:worker_threads:workerData; the value a"message"listener gets on aWorker,MessagePortorBroadcastChannelofworker_threads, onparentPort, or on a port of itsMessageChannel(.on,.once,.addListener, ...), when the parameter isn't annotated;receiveMessageOnPort(port).message. And every unannotated parameter of a listener on anEventEmitterofnode:eventsmade or declared without an event map (new EventEmitter();new EventEmitter<{ ready: [port: number] }>()is typed). A read ofworkerData.pathunder a test oftypeof workerData.path(in a?:, anif, 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
Functionwith(...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: unknownon the parameter of aworker_threads"message"listener or of an untypedEventEmitter'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 returnany(a.d.tsthat saysany, anaxioscall without a type argument). Wrap such a call inunsafe(...), which givesunknownfor a function returningany, or give it its type argument, thenvalidate<T>. - A value whose type only the type checker knows:
event.dataafterevent instanceof MessageEvent(which narrows toMessageEvent<any>), aFunctionthattypeof x === "function"narrows to, the property of a listener's parameter passed in from elsewhere (addEventListener("message", onMessage)withonMessage(event: MessageEvent)is reported at its annotation, though). - A receiver of unknown type:
this.socket.onmessage = (event) => event.data.xwithout 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)'sany[], a subclass ofEventEmitterand a stream's"data"listener ((chunk: any)). Annotate the parameterunknown. - A read through a sink the rule can't see: an
anyhanded to a method, to a function of another file or to a callback typed by its context, where that parameter is declaredunknown, is still reported. - What strict-lib retypes, when the tsconfig doesn't load it:
JSON.parse(text).nameandArray.isArray(value)on anunknowncompile 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 oftests/lib-any/allowed.txt, among them a generator's or iterator's return type (next()called by hand on anIterator<T>: writeIterator<T, undefined>), the bare globalopener,structuredCloneof anany, a Node stream's chunks (for await (const chunk of readable)), what anIDBObjectStore.getrequest gives, WebGL'sgetParameter, and one of the properties above read from a value that isn't shown to have that type: one narrowed by a test (result.reasonafterresult.status === "rejected"on aPromiseSettledResult,error.errorsaftererror instanceof AggregateError), what a lib function returns (AbortSignal.timeout(ms).reason), a package's value (MessageEventandCustomEventwithout a type argument are reported where the type is written, a field's annotation too, not at each read ofdata/detailthrough 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.