Skip to content
← Back to rules

typescript/no-unsafe-call 严格

💭 This rule requires type information.

它的作用

此规则禁止调用类型为 any 的值。

为什么这是不好的?

TypeScript 中的 any 类型会禁用类型检查。当你调用一个类型为 any 的值时,TypeScript 无法验证它是否确实是一个函数,也无法确认其预期参数或返回值。这可能导致运行时错误。

示例

此规则的 错误 代码示例:

ts
declare const anyValue: any;

anyValue(); // 不安全的调用

anyValue(1, 2, 3); // 不安全的调用

const result = anyValue("hello"); // 不安全的调用

// 链式不安全调用
anyValue().then().catch(); // 不安全

此规则的 正确 代码示例:

ts
declare const fn: () => void;
declare const fnWithParams: (a: number, b: string) => boolean;
declare const unknownValue: unknown;

fn(); // 安全

const result = fnWithParams(1, "hello"); // 安全

// 对 unknown 的类型守卫
if (typeof unknownValue === "function") {
  unknownValue(); // 经过类型守卫后是安全的
}

// 如果你确定,可显式进行类型断言
(anyValue as () => void)(); // 显式不安全但有明确意图

如何使用

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

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

参考资料