gpt4 book ai didi

Typescript:为什么 Promise 不可分配给 Promise | promise

转载 作者:行者123 更新时间:2023-12-02 01:24:12 27 4
gpt4 key购买 nike

type A = Promise<string> | Promise<number>
type B = Promise<string | number>

const a: A = Math.random() > 0.5 ? Promise.resolve('string') : Promise.resolve(1)
const b: B = Promise.resolve(Math.random() > 0.5 ? 'string' : 1)

class C {
fa(a: A) {
console.log(a)
}

fb(b: B) {
console.log(b)
}
}
const c = new C()

c.fa(a)
c.fb(b)

c.fa(b) /* <-- This produces an error:
Argument of type 'B' is not assignable to parameter of type 'A'.
Type 'Promise<string | number>' is not assignable to type 'Promise<string>'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.ts(2345)
*/
c.fb(a) // This works

为什么这段代码会产生错误?

附注 typescript 4.9.4

最佳答案

总的来说,F<T> | F<U> 是不正确的。相当于 F<T | U> ;这需要 F在其类型参数中是协变并且反之亦然(参见 Difference between Variance, Covariance, Contravariance and Bivariance in TypeScript用于方差描述)。而且编译器不一定会积极地将一种形式简化为另一种形式,即使它们是等效的。

但是,特别是Promise<T> | Promise<U>Promise<T | U>可以安全地互换。所以问题是:为什么在 TypeScript 中不会发生这种情况?

看来权威答案可以在 microsoft/TypeScript#51293 找到。根据the TS dev team lead :

The proposed reduction rule [equivalence of Promise<T> | Promise<U> with Promise<T | U>] is valid today, but I'm not sure what to make of it.

There's really nothing stopping TC39 from, tomorrow, deciding that Promises should have a .thenAgain method that runs a fresh invocation of the callback, and at that point the rule that Promise<T | U> === Promise<T> | Promise<U> stops being true. Then we'd be in quite a pickle.

This particular rule isn't something we've heard other feedback on despite obviously ~everyone interacting with Promises in one way or another, and there are no type checkers which don't reject at least some valid programs, so on net I don't see an action item here.

所以答案似乎是“低需求加上潜在的面向 future 的问题”。

关于Typescript:为什么 Promise<A | B> 不可分配给 Promise<A> | promise <B>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75184479/

27 4 0