Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 18.9 KiB · at 355e324

TSUS diagnostic codes

Generated from packages/cli/src/rules/registry.js by npm run docs. Do not edit by hand; tsus explain <CODE> prints the same text.

Code Rule Fix
TSUS000 Syntax error none
TSUS001 Classes are banned none
TSUS002 null is banned none
TSUS003 undefined is banned none
TSUS004 var is banned safe
TSUS005 throw is banned none
TSUS006 Malformed match expression none
TSUS100 Non-exhaustive match (runtime) none
TSUS200 Type error none
TSUS201 Non-exhaustive match none
TSUS202 Match arm does not fit the subject none
TSUS203 Match subject is not matchable none
TSUS300 ? outside a function returning Result or Option none
TSUS301 ? applied to something that is not a Result or Option none
TSUS302 ? propagates a value the function cannot return none
TSUS303 ? in a position that may not run none
TSUS401 any is banned safe
TSUS402 as casts are banned outside boundary files none
TSUS403 Non-null assertions are banned none
TSUS404 enum is banned unsafe
TSUS405 == and != are banned safe
TSUS406 Default exports are banned outside boundary files unsafe
TSUS407 Reassigning a parameter is banned none
TSUS408 let that is never reassigned safe
TSUS409 Mutating a parameter is banned unsafe
TSUS410 Result error types must be tagged none
TSUS411 Floating promises are banned unsafe
TSUS412 Unused Result none
TSUS413 Type-check suppressions are banned safe

TSUS000 syntax-error

Syntax error. Every other rule runs on the parsed tree, so nothing else can be checked until the file parses.

Rejected:

TypeScript
const total = (a: number, b: number): number => a + ;

Accepted:

TypeScript
const total = (a: number, b: number): number => a + b;

Hint: The file does not parse as TypeScript after macro expansion.

Fix: No automatic fix: the right change depends on intent.

TSUS001 no-class

Classes are banned. Classes mix data, behavior, identity and mutable state, and this rebinding is a classic source of bugs. Plain data plus functions is easier to verify, serialize and test.

Rejected:

TypeScript
class Counter {
  constructor(public count: number) {}
  next(): Counter {
    return new Counter(this.count + 1);
  }
}

Accepted:

TypeScript
type Counter = { readonly count: number };

const createCounter = (count: number): Counter => ({ count });
const next = (c: Counter): Counter => ({ count: c.count + 1 });

Hint: Use plain object types and functions.

Fix: No automatic fix: the right change depends on intent.

TSUS002 no-null

null is banned. null is an absent value that the type system lets you forget to check. Option makes absence a value you have to match on.

Rejected:

TypeScript
const find = (id: number): string | null => (id === 1 ? "ada" : null);

Accepted:

TypeScript
import { Some, None, type Option } from "@tsus/runtime";

const find = (id: number): Option<string> => (id === 1 ? Some("ada") : None);

Hint: Use Option from @tsus/runtime, or fromNullable at the boundary.

Fix: No automatic fix: the right change depends on intent.

TSUS003 no-undefined

undefined is banned. undefined is the second absent value. Having two of them doubles the checks and neither is enforced. Option replaces both.

Rejected:

TypeScript
const nickname: string | undefined = undefined;

Accepted:

TypeScript
import { None, type Option } from "@tsus/runtime";

const nickname: Option<string> = None;

Hint: Use Option from @tsus/runtime, or fromNullable at the boundary.

Fix: No automatic fix: the right change depends on intent.

TSUS004 no-var

var is banned. var is function-scoped and hoisted, so a binding can be read before it is assigned and leaks out of blocks.

Rejected:

TypeScript
var count = 0;

Accepted:

TypeScript
const count = 0;

Hint: Use const (preferred) or let.

Fix: tsus fix applies it (behavior is kept).

TSUS005 no-throw

throw is banned. A throw is an invisible second return type. Callers cannot see it in the signature and the compiler cannot make them handle it. Result<T, E> puts the failure in the type.

Rejected:

TypeScript
const parsePort = (raw: string): number => {
  const n = Number(raw);
  if (Number.isNaN(n)) {
    throw new Error("not a number");
  }
  return n;
};

Accepted:

TypeScript
import { Ok, Err, type Result } from "@tsus/runtime";

const parsePort = (raw: string): Result<number, "not a number"> => {
  const n = Number(raw);
  return Number.isNaN(n) ? Err("not a number") : Ok(n);
};

Hint: Return Result<T, E> from @tsus/runtime, or wrapSync/wrapAsync at the boundary.

Fix: No automatic fix: the right change depends on intent.

TSUS006 match-syntax

Malformed match expression. The match macro is expanded before TypeScript parses the file, so a malformed match has to be reported by the macro itself. One match uses either variant patterns or literal patterns, never both.

Rejected:

TypeScript
const label = match (opt) {
  Some(x) -> x,
};

Accepted:

TypeScript
const label = match (opt) {
  Some(x) => x,
  None => "none",
};

Hint: Arms look like: Variant(binding) => expression, "literal" => expression, or _ => expression, separated by commas.

Fix: No automatic fix: the right change depends on intent.

TSUS100 non-exhaustive-match-runtime

Non-exhaustive match (runtime). Thrown by the runtime if a value reaches a match that has no arm for it, which type-checked code only allows when outside data lies about its type. The compile-time check is TSUS201.

Rejected:

TypeScript
// data from JSON claims to be a Shape but has tag "Hexagon"
const name = (s: Shape): string =>
  match (s) {
    Circle(c) => "circle",
    Rect(r) => "rect",
  };

Accepted:

TypeScript
// validate outside data at the boundary before it becomes a Shape
const name = (s: Shape): string =>
  match (s) {
    Circle(c) => "circle",
    Rect(r) => "rect",
  };

Hint: Add an arm for every variant, or a _ arm.

Fix: No automatic fix: the right change depends on intent.

TSUS200 type-error

Type error. The whole project is type-checked by TypeScript in strict mode after macro expansion. Each TypeScript error is reported at its .tsus position with the TypeScript code in tsCode.

Rejected:

TypeScript
const port: number = "8080";

Accepted:

TypeScript
const port: number = 8080;

Hint: The original TypeScript diagnostic is in tsCode and the message.

Fix: No automatic fix: the right change depends on intent.

TSUS201 non-exhaustive-match

Non-exhaustive match. A match has to produce a value for every case. Missing a variant is the bug match exists to prevent, so it fails at compile time.

Rejected:

TypeScript
type Shape = Tagged<"Circle", number> | Tagged<"Square", number>;

const area = (s: Shape): number =>
  match (s) {
    Circle(r) => Math.PI * r * r,
  };

Accepted:

TypeScript
const area = (s: Shape): number =>
  match (s) {
    Circle(r) => Math.PI * r * r,
    Square(side) => side * side,
  };

Hint: Add an arm for every missing variant, or a _ arm to cover the rest.

Fix: No automatic fix: the right change depends on intent.

TSUS202 match-arm-mismatch

Match arm does not fit the subject. An arm for a variant the subject cannot hold is dead code, and usually a typo for a variant it can hold.

Rejected:

TypeScript
const area = (s: Shape): number =>
  match (s) {
    Circle(r) => Math.PI * r * r,
    Sqaure(side) => side * side,
  };

Accepted:

TypeScript
const area = (s: Shape): number =>
  match (s) {
    Circle(r) => Math.PI * r * r,
    Square(side) => side * side,
  };

Hint: Each pattern must be a variant tag (or literal value) the subject's type can actually hold.

Fix: No automatic fix: the right change depends on intent.

TSUS203 match-subject

Match subject is not matchable. Variant patterns read the subject's tag field and literal patterns compare primitive values, so the subject must be a tagged union or a primitive.

Rejected:

TypeScript
const describe = (d: Date): string =>
  match (d) {
    Some(x) => "some",
    None => "none",
  };

Accepted:

TypeScript
const describe = (d: Option<Date>): string =>
  match (d) {
    Some(x) => x.toISOString(),
    None => "none",
  };

Hint: Variant patterns need a tagged union (a tag field); literal patterns need a string, number, bigint, or boolean subject.

Fix: No automatic fix: the right change depends on intent.

TSUS300 try-outside-result-function

? outside a function returning Result or Option. ? returns early with the Err or None, so the enclosing function must be able to return one. Match arms are closures, and the top level has nothing to return from.

Rejected:

TypeScript
const total = (raw: string): number => {
  const n = parse(raw)?;
  return n;
};

Accepted:

TypeScript
const total = (raw: string): Result<number, ParseError> => {
  const n = parse(raw)?;
  return Ok(n);
};

Hint: Declare the enclosing function's return type as Result<T, E>, Option, or Promise<...> of one; ? cannot be used at top level or inside match arms, which are closures.

Fix: No automatic fix: the right change depends on intent.

TSUS301 try-on-non-result

? applied to something that is not a Result or Option. Only Result and Option have an Err or None to propagate.

Rejected:

TypeScript
const shout = (raw: string): Result<string, "empty"> => {
  const text = raw?;
  return Ok(text.toUpperCase());
};

Accepted:

TypeScript
const shout = (raw: string): Result<string, "empty"> =>
  raw === "" ? Err("empty") : Ok(raw.toUpperCase());

Hint: Only Result and Option values can be propagated with ?. In async code, await first: const x = await load()?;.

Fix: No automatic fix: the right change depends on intent.

TSUS302 try-incompatible-error

? propagates a value the function cannot return. The early return has to fit the function's declared return type: the error types must line up, and None cannot leave a function that returns Result.

Rejected:

TypeScript
const port = (env: Option<string>): Result<number, "bad port"> => {
  const raw = env?;
  return parsePort(raw);
};

Accepted:

TypeScript
const port = (env: Option<string>): Result<number, "bad port"> => {
  const raw = env.okOr<"bad port">("bad port")?;
  return parsePort(raw);
};

Hint: An Err must match the function's error type, and None can only propagate out of a function returning Option. Convert first (mapErr, okOr).

Fix: No automatic fix: the right change depends on intent.

TSUS303 try-conditional-position

? in a position that may not run. ? becomes an early return before its statement, so it cannot sit in code that might not run: a ?: branch, the right side of && || ??, or a loop condition.

Rejected:

TypeScript
const check = (raw: string): Result<boolean, ParseError> =>
  Ok(raw.length > 0 && (parse(raw)?) > 1);

Accepted:

TypeScript
const check = (raw: string): Result<boolean, ParseError> => {
  if (raw.length === 0) {
    return Ok(false);
  }
  const n = parse(raw)?;
  return Ok(n > 1);
};

Hint: ? is lowered to an early return before the statement, so it cannot sit in a ?: branch, the right side of && || ??, or a loop condition. Move it into its own statement.

Fix: No automatic fix: the right change depends on intent.

TSUS401 no-any

any is banned. any switches the type checker off for every value it touches, and it spreads: anything derived from an any is any too. unknown forces a check before use.

Rejected:

TypeScript
const parse = (raw: string): any => JSON.parse(raw);

Accepted:

TypeScript
const parse = (raw: string): unknown => JSON.parse(raw);

Hint: Use unknown and narrow it, or a precise type.

Fix: tsus fix applies it (behavior is kept).

TSUS402 no-as-cast

as casts are banned outside boundary files. A cast is a claim the compiler cannot check. Casts belong at the boundary, where outside data is validated once, not sprinkled through the program.

Rejected:

TypeScript
const user = JSON.parse(raw) as User;

Accepted:

TypeScript
// user.boundary.tsus: the one place outside data is trusted
import { z } from "zod";
import { Ok, Err, type Result } from "@tsus/runtime";

const UserSchema = z.object({ name: z.string() });
export type User = z.infer<typeof UserSchema>;

export const parseUser = (input: unknown): Result<User, "invalid user"> => {
  const out = UserSchema.safeParse(input);
  return out.success ? Ok(out.data) : Err("invalid user");
};

Hint: Validate the value (for example with zod) and return a Result, or move the cast into a *.boundary.tsus file.

Fix: No automatic fix: the right change depends on intent.

TSUS403 no-non-null-assertion

Non-null assertions are banned. x! tells the compiler a value cannot be absent without proving it. When the claim is wrong you get the crash Option exists to prevent.

Rejected:

TypeScript
const first = (xs: string[]): string => xs.find((x) => x.length > 0)!;

Accepted:

TypeScript
import { fromNullable } from "@tsus/runtime/boundary";

const first = (xs: string[]): string =>
  fromNullable(xs.find((x) => x.length > 0)).unwrapOr("");

Hint: Model the value as Option and match on it, or use unwrapOr.

Fix: No automatic fix: the right change depends on intent.

TSUS404 no-enum

enum is banned. enums are the one TypeScript feature that emits runtime code, numeric enums accept any number, and they do not narrow like literal unions. A union of literals is erasable, exhaustive in match, and serializes as itself.

Rejected:

TypeScript
enum Color {
  Red = "red",
  Green = "green",
}
const paint = (c: Color): string => c;
paint(Color.Red);

Accepted:

TypeScript
type Color = "red" | "green";
const paint = (c: Color): string => c;
paint("red");

Hint: Use a union of string literals: type Color = "Red" | "Green".

Fix: tsus fix --unsafe applies it; review the change, it can alter behavior.

TSUS405 no-loose-equality

== and != are banned. == coerces its operands ("1" == 1, "" == 0), which is almost never intended. With null and undefined gone, the one idiom that needed it (x == null) is gone too.

Rejected:

TypeScript
const isAdmin = (role: string): boolean => role == "admin";

Accepted:

TypeScript
const isAdmin = (role: string): boolean => role === "admin";

Hint: Use === or !==.

Fix: tsus fix applies it (behavior is kept).

TSUS406 no-default-export

Default exports are banned outside boundary files. A default export has no name, so every importer invents one and grep, rename and auto-import all get weaker. Named exports keep one name for one thing.

Rejected:

TypeScript
export default function greet(name: string): string {
  return `hi ${name}`;
}

Accepted:

TypeScript
export function greet(name: string): string {
  return `hi ${name}`;
}

Hint: Use a named export. Hosts that require a default export (Workers, framework pages) get a *.boundary.tsus file.

Fix: tsus fix --unsafe applies it; review the change, it can alter behavior.

TSUS407 no-param-reassign

Reassigning a parameter is banned. After a parameter is reassigned, the name no longer means what the caller passed, and every reader has to track which assignment is live.

Rejected:

TypeScript
const clamp = (n: number, max: number): number => {
  if (n > max) {
    n = max;
  }
  return n;
};

Accepted:

TypeScript
const clamp = (n: number, max: number): number => {
  const clamped = n > max ? max : n;
  return clamped;
};

Hint: Introduce a new const with a descriptive name.

Fix: No automatic fix: the right change depends on intent.

TSUS408 prefer-const

let that is never reassigned. let tells the reader to expect reassignment. When none happens the keyword is a false signal, and const lets the compiler hold the line.

Rejected:

TypeScript
let total = 0;
console.log(total);

Accepted:

TypeScript
const total = 0;
console.log(total);

Hint: Replace let with const.

Fix: tsus fix applies it (behavior is kept).

TSUS409 no-param-mutation

Mutating a parameter is banned. A function that mutates its argument changes data the caller still holds, which is spooky action at a distance. Returning new values keeps every function's effect visible in its return type.

Rejected:

TypeScript
const addItem = (cart: string[], item: string): string[] => {
  cart.push(item);
  return cart;
};

Accepted:

TypeScript
const addItem = (cart: string[], item: string): string[] => [...cart, item];

Hint: Return a new value instead: spread objects ({ ...p, x }), and use toSorted/toReversed/toSpliced or [...xs, item] for arrays.

Fix: tsus fix --unsafe applies it; review the change, it can alter behavior.

TSUS410 tagged-errors

Result error types must be tagged. Result<T, string> or Result<T, Error> says that something failed but not what, so callers cannot match on the cases. A tagged error type is a closed set the caller can handle exhaustively.

Rejected:

TypeScript
const load = (id: string): Result<User, string> =>
  id === "" ? Err("missing id") : Ok({ id });

Accepted:

TypeScript
type LoadError = "missing id" | Tagged<"NotFound", string>;

const load = (id: string): Result<User, LoadError> =>
  id === "" ? Err("missing id") : Ok({ id });

Hint: Use literals (Result<T, "not found" | "timeout">) or variants with a literal tag (or kind/type) field: Tagged<"NotFound", string> | { tag: "Timeout"; ms: number }.

Fix: No automatic fix: the right change depends on intent.

TSUS411 no-floating-promise

Floating promises are banned. A promise nobody awaits loses its result and its rejection. The work races the rest of the program and failures vanish.

Rejected:

TypeScript
const save = async (row: Row): Promise<Result<true, SaveError>> => write(row);

const handler = async (row: Row): Promise<string> => {
  save(row);
  return "done";
};

Accepted:

TypeScript
const handler = async (row: Row): Promise<string> =>
  match (await save(row)) {
    Ok(_) => "done",
    Err(e) => `failed: ${e.tag}`,
  };

Hint: await it, return it, or hand it to something that owns it (for example ctx.waitUntil(promise)).

Fix: tsus fix --unsafe applies it; review the change, it can alter behavior.

TSUS412 no-unused-result

Unused Result. A Result carries the failure case. Calling a function that returns one and dropping it is the same bug as an empty catch block.

Rejected:

TypeScript
const run = (): string => {
  saveConfig(config);
  return "saved";
};

Accepted:

TypeScript
const run = (): string =>
  match (saveConfig(config)) {
    Ok(_) => "saved",
    Err(e) => `not saved: ${e}`,
  };

Hint: match on it, propagate it with ?, or return it.

Fix: No automatic fix: the right change depends on intent.

TSUS413 no-ts-suppression

Type-check suppressions are banned. A suppression comment switches checking off for a line or a file with no record of why, which reopens every hatch the other rules close.

Rejected:

TypeScript
// @ts-ignore
const port: number = process.env.PORT;

Accepted:

TypeScript
import { fromNullable } from "@tsus/runtime/boundary";

const port: number = fromNullable(process.env.PORT).map(Number).unwrapOr(8080);

Hint: Fix the type error. If outside data is the problem, validate it in a *.boundary.tsus file.

Fix: tsus fix applies it (behavior is kept).