Skip to content
← Back to rules

typescript/no-unsafe-argument Pedantic

💭 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); // 明确不安全,但这是有意为之

如何使用

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

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

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

版本

此规则在 v1.12.0 中添加。

参考资料