gpt4 book ai didi

typescript - 为什么 `T extends "A "` and ` S extends "A"`没有重叠?

转载 作者:行者123 更新时间:2023-12-05 05:39:56 27 4
gpt4 key购买 nike

我对以下代码的 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)
}
}

playground

显然,TS 可能有重叠,但编译器说它们没有重叠。为什么会发生这种情况以及如何解决此错误?

最佳答案

我猜这个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;
}

为了让编译器满意,您可以转换为unknownany

  if (x as unknown === y) {
return true;
}

Playground

关于typescript - 为什么 `T extends "A "` and ` S extends "A"`没有重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72561377/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com