Linter · Rules
@typescript-eslint/no-unsafe-type-assertion
Disallow type assertions that narrow a type
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
Reported:
function toPort(value: string | number) {
return value as number;
}
interface Config {
port: number;
}
const config = JSON.parse("{}") as Config;
const loose = config as any;
Not reported:
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.