【问题标题】:Argument of type 'awaited T' is not assignable to parameter of type 'T''awaited T' 类型的参数不能分配给'T' 类型的参数
【发布时间】:2020-08-19 11:28:51
【问题描述】:

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

错误(TS2345):“等待 T”类型的参数不可分配给“T”类型的参数。 'T' 可以用与 'awaited T' 无关的任意类型实例化。

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.

另请参阅 Microsoft/TypeScript/#37664 中的 this comment

使用 Promise.all 在泛型函数中推断错误的返回类型

编辑

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

这是在使用Version 4.0.0-dev.20200504时其他部分代码这里没有显示,问题在this GitHub issue中有详细说明。

Playground 3.9.0-dev.20200324

Playground Nightly

Playground 3.8.3

【问题讨论】:

  • 似乎在 TS v3.8.3 和 Nightly 中运行良好:typescript playground
  • @jtbandes 你是对的,因为等待东西的其他问题我被那个版本的 TS (3.9.0-dev.20200324) 卡住了,我也添加了指向操场的链接,我也不知道使用此 TS 版本时是否有解决方法:-(
  • 不要使用3.9.0-dev.20200324 版本 - 如果需要,请切换到 3.9 测试版。 20200324 的 dev 版本仍然包含 awaited 类型运算符,同时由于一些存在的 incompatibility issues 而被延迟到更高的 TS 版本。

标签: typescript generics asynchronous types async-await


【解决方案1】:

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)
  );
}

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

【讨论】:

  • 好的,我可以return promise.then(t =&gt; funct((t as any) as T)); 或者我可以return promise.then(t =&gt; funct((t as unknown) as T)); ```
  • 我不确定在这个特定示例中使用 unknownany 之间的区别...
  • 在这种情况下无关紧要,因为您明确指定了输出类型Promise&lt;any&gt;。但是,当您执行 Promise&lt;unknown&gt; 并尝试稍后做一些有价值的事情时,它不会允许您(除非您将其转换为任何值)。
猜你喜欢
  • 2018-05-08
  • 2019-07-27
  • 2022-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 2016-07-31
  • 1970-01-01
相关资源
最近更新 更多