Skip to content
← Back to rules

typescript/no-unsafe-type-assertion Suspicious

💭 This rule requires type information.

功能说明

禁止会缩小类型范围的不安全类型断言。

为什么这很糟糕?

会缩小类型范围的类型断言会绕过 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;

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/no-unsafe-type-assertion": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/no-unsafe-type-assertion": "error",
  },
});
bash
oxlint --type-aware --deny typescript/no-unsafe-type-assertion

版本

此规则新增于 v1.12.0。

参考资料