- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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>
withPromise<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 thatPromise<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/
我是一名优秀的程序员,十分优秀!