no-unchecked-cast
value as T, <T>value, the non-null assertion value! and the definite assignment assertion let x!: T are not allowed (as const is).
Why: a cast tells TypeScript to trust you without checking. When you're wrong, the program crashes somewhere else, later. Check the value instead, and TypeScript narrows the type for you.
✕ Rejectedno-unchecked-cast
ts
type Point = { readonly x: number; readonly y: number };
export function toPoint(value: unknown): Point {
return value as Point;
}
export function first(items: readonly string[]): string {
return items[0]!;
}✓ Accepted0 diagnostics
ts
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import type { Option, Result } from "@evobug_com/safe-ts-std/result";
type Point = { readonly x: number; readonly y: number };
export function toPoint(value: unknown): Result<Point, JsonError> {
return validate<Point>(value);
}
export function first(items: readonly string[]): Option<string> {
return items[0];
}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 type { Option, Result } from "@evobug_com/safe-ts-std/result";
type Point = { readonly x: number; readonly y: number };
export function toPoint(value: unknown): Result<Point, JsonError> {
return __jsonValidate<Point>(value, __v0);
}
export function first(items: readonly string[]): Option<string> {
return items[0];
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "x": number; "y": number; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["x"];
if (typeof __j1 !== "number") return __jsonFail(p + ".x", "number", __j1);
const __j2 = __j1;
const __j3 = v["y"];
if (typeof __j3 !== "number") return __jsonFail(p + ".y", "number", __j3);
const __j4 = __j3;
const out: { "x": number; "y": number; } = { "x": __j2, "y": __j4 };
return out;
}A cast that only adds a field to assign it ((el as HTMLElement & { orderId: string }).orderId = id) gets a hint in its help: declare the field once with module augmentation (declare module "pkg" { interface Sprite { tag?: Option<string> } }, or declare global for a global type), and assign it without a cast.
✅ Also accepted: a test TypeScript narrows by, written where the value is used (a hand-written value is T is a cast too: no-type-predicate)
✓ Accepted0 diagnostics
ts
export function textLength(value: unknown): number {
return Array.isArray(value) && value.every((item) => typeof item === "string") ? value.join("").length : 0;
}a[i]! where the bound is checked
With noUncheckedIndexedAccess (which SAFE-TS asks for), bytes[i] is number | undefined even where a loop has just checked the bound. a[i]! is allowed where the checker can prove the index in bounds: an integer, >= 0 and < a.length at the moment of the read.
✓ Accepted0 diagnostics
ts
type Line = { readonly price: number; readonly qty: number };
type Cart = { readonly lines: readonly Line[] };
export function checksum(bytes: Uint8Array): number {
let sum = 0;
for (let i = 0; i < bytes.length; i++) sum = (sum + bytes[i]!) % 65521;
return sum;
}
export function changes(cart: Cart): number {
let moved = 0;
// A member path, a start other than 0, the neighbour before.
for (let i = 1; i < cart.lines.length; i++) moved += cart.lines[i]!.qty - cart.lines[i - 1]!.qty;
// Descending, with an extra condition.
for (let i = cart.lines.length - 1; i >= 0 && moved < 100; i--) moved += cart.lines[i]!.price;
return moved;
}
export function invoice(prices: readonly number[], quantities: readonly number[]): number {
if (prices.length !== quantities.length) return 0;
let sum = 0;
for (let i = 0; i < prices.length; i++) sum += prices[i]! * quantities[i]!;
return sum;
}What counts, exactly:
- The array is a variable or a property path:
items,cart.lines,this.#queue(a!inside it,cart!.lines, is reported on its own). Aconstnaming it (const lines = cart.lines,const { lines } = cart) is the same array. A call result (load()[0]!) or an element (rows[r]![c]!) is not; name the row first. - The index is an integer the checker can follow: a literal,
x.length, a loop index, aconstholding one,+and-of those,x | 0,x >>> 0,x & mask,x % n,Math.min,Math.max,c ? a : b. Anumberparameter isn't one (it can be0.5): checkNumber.isInteger(i)with the bounds. Aletis one when it starts as an integer and is only assigned integers (i++,i += 2,i = j + 1). - The check: a comparison of the index (or
i + k,i - k) with an integer, where it holds:- a
forloop:for (let i = <start>; <test>; <update>), where the update (i++,i--,i += k,i -= k) is the only assignment ofi. The start is any integer (0,k + 1of another loop's index,a.length - 1): ascending, it is a lower bound; descending, an upper one. The test is one comparison or several joined by&&:i < a.length,i + 1 < a.length,i <= a.length - 2,i < 4,i >= 1,i < a.length && !found; - the body of a
whileloop, the right side of&&(i < a.length && a[i]! > 0), the branches ofifand?:, and the rest of a block after an early exit (if (i >= a.length) return;,if (k === 0) continue;), until the index is assigned; - a length check: after
if (items.length === 0) return;(orassert.ok(items.length > 0)ofnode:assert, vitest or chai),items[items.length - 1]!anditems[0]!are in bounds. So they are in the body offor (const x of items)(alsoitems.entries()) and in a callback ofitems.map,forEach,reduce,filter,some,every,findand the like, which run for an element.
- a
- A second array of the same length:
i < a.length && i < b.length; a length check before (if (a.length !== b.length) return;, or insideif (a.length === b.length)); or an array made from the first:const b = a.map(...)(alsotoSorted,toReversed,with,slice(),[...a],[...a].sort(...)),new Float64Array(a.length),Array.from({ length: a.length }, ...). A length check of the first holds for the second. - A known length: a parameter or variable typed as a tuple (
readonly [A, B, C], also through atypealias in the same file;[T, ...T[]]has its leading elements at least), or aconstarray literal (as const, areadonlytype,Object.freeze, or never shrunk; a literal that may shrink later still has its elements until then). That bounds literal indices (i < 4over four corners), clamps (SIZES[Math.max(0, Math.min(SIZES.length - 1, n | 0))]!) and an index whose declared type is a union of integer literals in range (size: 0 | 1 | 2, also a field:SIZES[item.size]!). - Nothing in between changes it. Between the check and the read, nothing may change the array's length or replace it: assigning it or a part of its path (
cart.lines = [],cart = other), a shrinking method (pop,shift,splice,length = n), a method of a part of its path (cart.reset()), passing it or a part of its path to a call (removeEmpty(cart)), a call to a callback (a parameter, a computed function) or to a local function whose body may change it, anawaitoryield, and for a module-level array a call to a function of the project. A check in a loop test holds again on every iteration, so a change after the read in the same iteration is fine; a check before the loop (a descending start,const n = a.length, an equal length) must hold for the whole loop. An array also kept under another name the checker doesn't follow (alet, an object) gets no bounds at all; one stored in a container (list.push(a),map.set(key, a)) gets none where the container is used, or a local function orawaitruns, between the check and the read.
A read in a callback (items.forEach(() => a[i]!)) gets no bounds from around it: it may run later. Neither does a callback's own index parameter ((item, i) => other[i]!): write the index loop. An array whose elements may be undefined by its declared type (Option<T>[], (T | undefined)[]) or that has holes (new Array(n), or a write anywhere in the file the checker can't show is inside it or at its end: slots[n] = 1, delete a[i], a.length = n) isn't covered: a read in bounds can still be undefined there. A typed array has no holes (a write outside it is ignored). sparse-array-write reports the writes that make holes.
The message says why a read isn't accepted, and what to use instead:
✕ Rejectedno-unchecked-cast
ts
type Line = { readonly price: number };
// `i` can be 0, so `i - 1` can be -1: start at 1, or test `i >= 1`.
export function gaps(lines: readonly Line[]): number {
let sum = 0;
for (let i = 0; i < lines.length; i++) sum += lines[i]!.price - lines[i - 1]!.price;
return sum;
}✕ Rejectedno-unchecked-cast
ts
// `start` is any number: `0.5` or `-1` would read `undefined`.
export function from(prices: readonly number[], start: number): number {
let sum = 0;
for (let i = start; i < prices.length; i++) sum += prices[i]!;
return sum;
}The other ways to read an element: a tuple type, where TypeScript knows every element exists; a[i] ?? fallback; const x = a[i]; if (x === undefined) ...; or for (const x of a) when the index isn't needed:
✓ Accepted0 diagnostics
ts
export function from(prices: readonly number[], start: number): number {
let sum = 0;
for (let i = start; i < prices.length; i++) sum += prices[i] ?? 0;
return sum;
}let x!: T (and a class field name!: T) is the same promise as x!, made once for every read: TypeScript stops checking that it is assigned before it is used. The usual reason is a promise resolved from outside; Promise.withResolvers() gives both at once:
✕ Rejectedno-unchecked-cast
ts
export function deferred(): { promise: Promise<number>; done: (value: number) => void } {
let resolve!: (value: number) => void;
const promise = new Promise<number>((r) => {
resolve = r;
});
return { promise, done: (value) => resolve(value) };
}✓ Accepted0 diagnostics
ts
export function deferred(): { promise: Promise<number>; done: (value: number) => void } {
const { promise, resolve } = Promise.withResolvers<number>();
return { promise, done: resolve };
}For other values: initialize them, or declare them T | undefined and check them.
For reads at a computed position (buf[pos++] after checking need(n) once), DataView#getUint8(pos) returns a number and throws a RangeError past the end.
For a field a package's type lacks, a protected member of a library class, or a key built from a template, see Typing without casts.
mut<T>(value) with a type argument is a cast too: TypeScript accepts any narrower value for the type written there, so mut<Animal[]>(dogs) lends a Dog[] where a cat may be pushed (Mut itself refuses mut(dogs)). It is reported unless the value is a fresh literal (mut<number[]>([]), mut<Draft>({ text: "" })), which nothing else holds. Write mut(value).
The other claims TypeScript takes on trust are their own rules: a type predicate or assertion signature (no-type-predicate) and an overload over a looser implementation (no-overload).
What the rule can't see: for a[i]!: another object holding the same array and changing it during the loop (stored there earlier, or by a function the loop calls), getters and setters, Proxy objects, iterators and other code run implicitly, a typed array whose buffer is transferred or resized, a callback parameter typed with an imported function type that the loop hands to another function, element types it can't see (an Option<T>[] reached through a property), and holes made in another file (an array passed in that a caller wrote past its end; sparse-array-write reports those writes where they are).