Skip to content
← Back to rules

typescript/no-unsafe-argument 严谨

💭 This rule requires type information.

它的作用

此规则禁止调用函数时传递 any 类型的参数。

为什么这是不好的?

TypeScript 中的 any 类型是一个危险的“逃逸通道”,绕过了类型系统。使用 any 会禁用大多数类型检查规则,通常存在安全隐患。当你将一个 any 类型的值传递给函数时,该函数调用就失去了类型安全性。

示例

以下为 错误 的代码示例:

ts
declare const anyValue: any;

function takesString(str: string): void {
  console.log(str.length);
}

takesString(anyValue); // 不安全

declare function takesNumber(num: number): number;
const result = takesNumber(anyValue); // 不安全

以下为 正确 的代码示例:

ts
declare const stringValue: string;
declare const numberValue: number;
declare const unknownValue: unknown;

function takesString(str: string): void {
  console.log(str.length);
}

takesString(stringValue); // 安全

// 使用类型守卫来安全地处理 unknown
if (typeof unknownValue === "string") {
  takesString(unknownValue); // 经过类型守卫后是安全的
}

// 如果你确定类型,可以使用显式类型断言
takesString(unknownValue as string); // 显式不安全,但出于明确意图

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/no-unsafe-argument": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unsafe-argument

参考资料