@typescript-eslint/no-unsafe-type-assertion

Disallow type assertions that narrow a type

needs types

Also called typescript-eslint/no-unsafe-type-assertion, typescript/no-unsafe-type-assertion

value as T makes TypeScript treat value as a T without a check. If T is narrower than the real type, the claim can be false, and the code that follows works with a value that isn't what its type says.

An assertion from or to any is reported as well. An assertion to a wider type is always true, so it's allowed, and so is as const.

Configure#

Off by default. This rule needs types, so turning it on makes bun lint type check your code first.

bunfig.toml
[lint.rules]
"@typescript-eslint/no-unsafe-type-assertion" = "error" # or "warn"

Examples#

example.ts1 problem
function toPort(value: string | number) {
  return value as number;
}
example.ts2 problems
interface Config {
  port: number;
}

const config = JSON.parse("{}") as Config;
const loose = config as any;
example.tsNo problems
function toPort(value: string | number) {
  return typeof value === "number" ? value : Number(value);
}

const port = 3000 as string | number;
const modes = ["dev", "prod"] as const;

When not to use it#

You can't check some values in a way TypeScript understands, such as the result of document.querySelector() when you know the markup. If your code has many of these, the rule reports assertions you can't avoid.