@typescript-eslint/no-unsafe-type-assertion
Disallow type assertions that narrow a type
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.
[lint.rules]
"@typescript-eslint/no-unsafe-type-assertion" = "error" # or "warn"Examples#
function toPort(value: string | number) {
return value as numberUnsafe type assertion: type number is more narrow than the original type.;
}interface Config {
port: number;
}
const config = JSON.parse("{}") as ConfigUnsafe assertion from any detected: consider using type guards or a safer assertion.;
const loose = config as anyUnsafe assertion to any detected: consider using a more specific type to ensure safety.;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.