typescript/no-unsafe-type-assertion 可疑
它的作用
禁止对类型进行可能缩小类型的不安全断言。
为什么这是不好的?
缩小类型的类型断言会绕过 TypeScript 的类型检查,可能导致运行时错误。而扩大类型的类型断言是安全的,因为 TypeScript 对该类型了解得更少。与其使用类型断言来缩小类型,不如依赖类型守卫,这有助于避免因不安全的类型断言而导致的潜在运行时错误。
示例
此规则的 错误 代码示例:
ts
function f() {
return Math.random() < 0.5 ? 42 : "oops";
}
const z = f() as number;
const items = [1, "2", 3, "4"];
const number = items[0] as number;此规则的 正确 代码示例:
ts
function f() {
return Math.random() < 0.5 ? 42 : "oops";
}
const z = f() as number | string | boolean;
const items = [1, "2", 3, "4"];
const number = items[0] as number | string | undefined;如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/no-unsafe-type-assertion": "error"
}
}bash
oxlint --type-aware --deny typescript/no-unsafe-type-assertion