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

标签 typescript typescript-generics

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

相关文章:

typescript - 作为对象属性的 Svelte 组件

typescript - 禁止显式类型参数或约束联合类型参数以提高类型安全性

arrays - Typescript 泛型,获取数组内容的类型

angular - app.component.ts 中的 Ionic 3 登录和检查语句

angular - 以 Angular 5 迭代复杂的 JSON 结构

typescript 在编译时减去两个数字

TypeScript 泛型 : 'type is not assignable to type T'

angular - Typescript 中的解构赋值

typescript - 如何使用 TypeScript、Jest 和 Enzyme 在 React 中测试按钮点击

angular - Angular CLI 生成的 "spec.ts"文件有什么用?