TypeScript Tooltip for function overloaded to mimic variadic types infers wrong overload when called with trailing comma

0qx6xfy6  于 9个月前  发布在  TypeScript
关注(0)|答案(3)|浏览(82)

TypeScript版本: 2.7.0-dev.20180418
搜索词: Intellisense重载,工具提示重载
代码

  1. function test<A>(a: A): true;
  2. function test<A, B>(a: A, b: B): false;
  3. function test<T>(...values: T[]): boolean {
  4. return values.length === 1;
  5. }
  6. declare function assertTrue(truth: true): void;
  7. const noComma = test( // test<string>(a: string): true
  8. 'foo'
  9. )
  10. assertTrue(noComma);
  11. const withComma = test( // test<string, {}>(a: string, b: {}): false, but withComma: true
  12. 'foo',
  13. );
  14. assertTrue(withComma);
  15. assertTrue(test( // test<string, {}>(a: string, b: {}): false, but no error
  16. 'foo',
  17. ));

预期行为:

对于 noCommawithComma 和直接传递给 assertTruetest<A>(a: A): true 版本,推断出的 test 的版本(如悬停工具提示所示)。

实际行为:

对于 withComma 和直接传递的版本,推断出的 test<A, B>(a: A, b: B): false 是特定的 test<string, {}>(a: string, b: {}): false
尽管如此,withComma 的类型是 true,并且在调用 assertTrue 时或直接传递时没有报告错误。

** playground链接:**here
相关问题:#7279

e37o9pze

e37o9pze1#

我们使用尾随逗号作为用户正在输入函数的指示,并且参数列表是不完整的。恰好现在允许尾随逗号成为语言的一部分。我们应该将其限制在签名帮助中,而不是在快速信息中也使用。

ars1skjm

ars1skjm2#

PRs感激不尽。

hwamh0ep

hwamh0ep3#

这个问题的影响范围不仅仅是快速信息提示。例如,如果一个lint工具使用了错误的推断重载,那么如果该重载被标记为已弃用,就会导致错误/警告。在使用RxJS.map(..)操作符时,我恰好遇到了这种情况,它的签名如下(当时):

  1. export function map<T, R>(project: (value: T, index: number) => R): OperatorFunction<T, R>;
  2. /** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
  3. export function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>;

当然,过时的API最终会被移除,但在那之前,检查已弃用代码的Linters可能会让我们很头疼:

  1. const source = from([1, 2, 3, 4, 5]);
  2. source.pipe(map(val => val + 10)); // complaint
  3. source.pipe(
  4. map( // non-complaint: the deprecated overload is inferred
  5. val => val + 10,
  6. ),
  7. );

我可以尝试提交PR,但如果有人能指出正确的方向,那就太好了,因为这是我第一次为TypeScript的代码库做出贡献。
提前感谢!

展开查看全部

相关问题