【问题标题】:could be instantiated with a different subtype of constraint '{}' typescript error可以用不同的约束子类型来实例化'{}'打字稿错误
【发布时间】:2020-01-22 16:23:48
【问题描述】:

升级到 typescript 3.5 后,我经常看到这个错误。

可以用不同的约束子类型“{}”打字稿错误来实例化

我不知道它是什么意思,它总是指空的{} 类型。

如果您查看第 34 行的 this playground,我不知道可以用不同的子类型实例化什么,甚至不知道子类型可能是什么。

这是一个打字稿生成的消息,我认为{} 是添加到错误消息中的默认类型。

This github issue 存在,但我仍在努力理解它

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我不明白其余代码的作用,但手头的问题归结为:

    function map2<A, B>(x: A|undefined, fn: (a: A) => B): B|undefined  {
      if (x === undefined) {
          return x;
      } else {
          return fn(x);
      }
    }
    

    这不检查,因为A也可以包含undefined,TS无法决定是在第一个分支返回A还是undefined

    这可以通过告诉 TS A 永远不会未定义来轻松解决:

    function map2<A extends {}, B>(x: A|undefined, fn: (a: A) => B): B|undefined  {
      if (x === undefined) {
          return x;
      } else {
          return fn(x);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 2021-11-24
      • 2020-05-30
      • 2020-03-27
      • 2021-06-26
      • 2022-01-20
      • 2021-02-13
      • 2020-11-25
      • 2019-12-13
      相关资源
      最近更新 更多