作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对以下代码的 typescript 编译错误感到困惑:
function f<T extends "A", S extends "A">(x: T, y: S) {
if (x === y) {
// ERROR: This condition will always return 'false' since the types 'T' and 'S' have no overlap. ts(2367)
}
}
显然,T
和S
可能有重叠,但编译器说它们没有重叠。为什么会发生这种情况以及如何解决此错误?
最佳答案
我猜这个comment RyanCavanaugh 的著作也适用于您的案例:
=== is only allowed between two operands if there is a "comparable" type relationship between them. This is similar to the check that determines if a type assertion is legal, with some extra special cases.
要从编译器中查看更有意义的错误,请尝试转换:
function f<T extends "A", S extends "A">(x: T, y: S) {
/**
* Conversion of type 'T' to type 'S' may be a mistake
* because neither type sufficiently overlaps with the other.
* If this was intentional, convert the expression to 'unknown' first.
*
* 'T' is assignable to the constraint of type 'S',
* but 'S' could be instantiated with a different subtype of constraint '"A"'.
*/
const a = x as S;
}
为了让编译器满意,您可以转换为unknown
或any
。
if (x as unknown === y) {
return true;
}
关于typescript - 为什么 `T extends "A "` and ` S extends "A"`没有重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72561377/
我是一名优秀的程序员,十分优秀!