typescript - 类型 'T' 不可分配给 TypeScript 中的类型 'T extends T ? T : T'

标签 typescript

我在我的项目中遇到了这个问题,下面是可以重现它的最少代码。我想知道是不是TypeScript的bug,还是我用错了。 (实际代码比较复杂,但是错误是一样的)

错误是:类型“T”不能分配给类型“T extends T”? T : T'。

我在 TypeScript 3.0.3 和 3.3.1 上测试过

function test<T>(arg: T) {
  let x: T extends T ? T : T;
  x = arg;
}

最佳答案

Typescript 不会尝试解析条件类型,因此即使这个看似微不足道的示例也无法分配。我猜你的真实示例更复杂,但同样的想法仍然适用。

只有当条件类型相同时才允许赋值:

function test<T>(arg: T) {
  let x: T extends T ? T : T;
  let y: T extends T ? T : T;
  x = y; //ok 
}

关于typescript - 类型 'T' 不可分配给 TypeScript 中的类型 'T extends T ? T : T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54659459/

相关文章:

javascript - 如何初始化具有数组的 Typescript 接口(interface)?

javascript - 类型错误 : Cannot read property 'http' of undefined

javascript - <a> 元素不会重定向到另一个页面且不可点击

angular - 在 Angular 4 Reactive Forms 中提交时显示验证消息

javascript - Magnific Popup 的 Typescript 定义文件

javascript - 传递联合类型的 Prop 以 react 需要联合中的一种类型的子组件

javascript - Visual Studio Code Language Server - 如何验证工作区中的所有文件

typescript - 如何在 Typescript 接口(interface)中为函数定义返回类型 void?

typescript - Visual Studio Code 中的 TS Lint 突然提示 wrong lint 错误

Angular 7 : Build Prod Error: Property 'value' does not exist on type 'Component'