typescript - 类型 'awaited T' 的参数不可分配给类型 'T' 的参数

标签 typescript generics asynchronous types async-await

我收到此错误消息,不知道该怎么办(如下面的EDIT 所述,我使用的是 TS version 3.9.0-dev.20200324) ...

error(TS2345): Argument of type 'awaited T' is not assignable to parameter of type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'awaited T'.

Screen capture of the problem -- Code as text below -- Pop N' Lock Theme by Luxcium ✨

TypeScript 代码:lib/functional/promise-or-not.ts


// ... [more code]

export async function thenified<T>(
  promise: Promise<T>,
  funct: <R>(t: T) => R,
): Promise<any> {
  return promise.then(
    t => funct(t)
  );
}

输出:tsc Version 3.9.0-dev.20200324

% ❯  tsc # 3.9.0-dev.20200324 
lib/functional/promise-or-not.ts:10:16 - error TS2345: Argument of type 'awaited T' is not assignable to parameter of type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'awaited T'.

10     t => funct(t)
                  ~
Found 1 error.

另见 this comment在 Microsoft/TypeScript/#37664 中:

Wrong return type inference in a generic function using Promise.all

编辑

由于在使用其他 TS 版本时我的代码中存在不同的其他问题,我无法使用 Version 3.9.0-dev.20200324

这是在使用Version 4.0.0-dev.20200504时其他部分的代码这里就不展示了,问题详见this GitHub issue .

Many more problems using current version

Playground 3.9.0-dev.20200324

Playground Nightly

Playground 3.8.3

最佳答案

t 转换为 any

export async function thenified<T>(
  promise: Promise<T>,
  funct: <R>(t: T) => R,
): Promise<any> {
  return promise.then(
    t => funct(t as any)
  );
}

糟糕的解决方法,但你能做什么。

关于typescript - 类型 'awaited T' 的参数不可分配给类型 'T' 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61602377/

相关文章:

javascript - 如何使用javascript将对象转换为二维数组

typescript - 从 SomeType<T> 中提取类型 T

angularjs - 在 mat-table 的 mat-cell 中实现 if else 条件 - Angular 5

generics - Kotlin 中扩展函数的多态性

c# - .NET 2.0 : Invoking Methods Using Reflection And Generics Causes Exception

knockout.js - Typescript 类继承 : override ko. 计算方法

C# 泛型和转换问题

python-3.x - 在 Python 3.5 中,关键字 "await"是否等同于 "yield from"?

kotlin - 为什么协程作用域启动由不同的线程运行?

c# - 无法读取 ASP.NET WebApi Controller 中的 Request.Content