【问题标题】:Typescript generic function doesn't complain about callback return typeTypescript 泛型函数不会抱怨回调返回类型
【发布时间】:2020-06-09 07:02:04
【问题描述】:

Typescript 泛型函数不会抱怨回调返回类型。它不应该抱怨类型与对象不匹配吗?为什么这是一个有效的打字稿?

const a = <T>(shape: T | (() => T)): T => {
    return shape instanceof Function ? shape() : shape;
}

const func = () => ({ x: '', o: '' });
a<{ x: string }>(func); // this should fail to compile

a<{ x: string }>({ x: '', o: '' }); // fails to compile

Playground Link

【问题讨论】:

  • 您的 Playground 链接用消息Argument of type '{ x: string; o: string; }' is not assignable to parameter of type '{ x: string; } | (() =&gt; { x: string; })'. Object literal may only specify known properties, and 'o' does not exist in type '{ x: string; } | (() =&gt; { x: string; })' 强调了一些代码 - 这不正是您所期望的吗?
  • @Jamiec 令人困惑的是为什么它没有在代码的 2 部分下划线。有不一致的地方。有趣的是,通过 const func = () =&gt; ({ g: '',f:'' }); 失败,这意味着至少有一些类型检查在起作用。
  • @spender 正确,我希望它在两个调用中都会失败。看起来只有当函数返回类型完全不匹配泛型类型时它才会完全失败。
  • 你这样定义的函数,隐式返回任何类型。使用正确的返回类型将您的 const 输入为 fn,它会抱怨
  • 这是因为过多的属性检查只针对对象字面量进行。如果您定义 const obj = {x: '', o: ''}; 然后调用 a&lt;{x: string}&gt;(obj); 这不是错误,因为 obj 是一个变量,而不是文字。另一方面,如果你直接传递 function literal 而不是定义一个名为 func 的常量,那么它不会报错,因为 function literal 不是 对象字面量.

标签: typescript


【解决方案1】:

这是一个已知的 TypeScript 错误。 Github issue 需要 fix

没有找到合适的解决方法

【讨论】:

    【解决方案2】:

    上下文类型(在您的情况下为 a&lt;{ x: string }&gt;(func); )不执行过多的属性检查,没有关于此的规范,所以也许这是设计使然

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2021-10-06
      • 2020-07-05
      • 1970-01-01
      • 2020-01-23
      • 2021-03-24
      • 1970-01-01
      相关资源
      最近更新 更多