Skip to content
← Back to rules

typescript/no-misused-promises 严谨

💭 This rule requires type information.

它的作用

此规则禁止在逻辑位置(如 if 语句)中传递 Promise,这些位置虽然在 TypeScript 编译器允许范围内,但未得到正确处理。这类情况通常由于缺少 await 关键字,或对异步函数如何被处理/等待的理解错误所致。

为什么这是问题?

误用的 Promise 可能导致崩溃或其他意外行为,除非存在全局未处理的 Promise 处理程序。

示例

以下为该规则的 错误 代码示例:

ts
// 条件中的 Promise:
const promise = Promise.resolve("value");
if (promise) {
  // 执行某些操作
}

// 期望返回 `void` 的地方却使用了 Promise:
[1, 2, 3].forEach(async (value) => {
  await fetch(`/${value}`);
});

// 展开 Promise:
const getData = () => fetch("/");
console.log({ foo: 42, ...getData() });

以下为该规则的 正确 代码示例:

ts
// 在条件中 `await` Promise 以获取其值:
const promise = Promise.resolve("value");
if (await promise) {
  // 执行某些操作
}

// 使用带有 `await` 的 `for-of` 循环(而非 `forEach`):
for (const value of [1, 2, 3]) {
  await fetch(`/${value}`);
}

// 展开来自 Promise 的数据,而不是展开 Promise 本身:
const getData = () => fetch("/");
console.log({ foo: 42, ...(await getData()) });

配置

此规则接受一个包含以下属性的配置对象:

checksConditionals

type: boolean

default: true

是否检查在条件中使用了 Promise。 当为 true 时,禁止在期望布尔值的位置使用 Promise。

checksSpreads

type: boolean

default: true

是否检查在展开语法中使用了 Promise。 当为 true 时,禁止展开 Promise 值。

checksVoidReturn

type: object | boolean

checksVoidReturn.arguments

type: boolean

default: true

是否检查作为参数传入返回 void 函数的返回 Promise 的函数。

checksVoidReturn.attributes

type: boolean

default: true

是否检查在期望返回 void 的 JSX 属性中返回 Promise 的函数。

checksVoidReturn.inheritedMethods

type: boolean

default: true

是否检查覆盖了返回 void 的继承方法的返回 Promise 的方法。

checksVoidReturn.properties

type: boolean

default: true

是否检查分配给期望返回 void 的对象属性的返回 Promise 的函数。

checksVoidReturn.returns

type: boolean

default: true

是否检查从返回 void 的函数中返回的 Promise 值。

checksVoidReturn.variables

type: boolean

default: true

是否检查赋值给类型为返回 void 的变量的返回 Promise 的函数。

如何使用

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

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

参考资料