简体   繁体   English

如何在 typescript 4.5.4 中定义方法返回类型的映射类型?

[英]How to define mapped type for method return types in typescript 4.5.4?

In typescript 4.4.4 this code compiled fine:在 typescript 4.4.4 中,这段代码编译得很好:

/**
 * type to get only those properties that are functions
 */
type FunctionProperties<T> = {
  [P in keyof T]: T[P] extends (...args: any) => any ? P : never;
}[keyof T];

type ReturnTypeOfMethod<T, K extends FunctionProperties<T>> = ReturnType<T[K]>;

see Playground 4.4.4 example参见Playground 4.4.4 示例

But the same code fails to compile in typescript 4.5.4 - see Playground 4.5.4 example但是相同的代码无法在 typescript 4.5.4 中编译 - 请参阅Playground 4.5.4 示例

Type 'T[K]' does not satisfy the constraint '(...args: any) => any'.
  Type 'T[FunctionProperties<T>]' is not assignable to type '(...args: any) => any'.
    Type 'T[T[keyof T] extends (...args: any) => any ? keyof T : never]' is not assignable to type '(...args: any) => any'.
      Type 'T[keyof T]' is not assignable to type '(...args: any) => any'.
        Type 'T[string] | T[number] | T[symbol]' is not assignable to type '(...args: any) => any'.
          Type 'T[string]' is not assignable to type '(...args: any) => any'.

The strange thing is that the ReturnTypeNumber type still shows the expected type ( number in this example).奇怪的是ReturnTypeNumber类型仍然显示预期的类型(本例中为number )。
Any idea why this does not work anymore or how to fix this (using @ts-ignore is not a fix)?知道为什么这不再起作用或如何解决此问题(使用@ts-ignore不是解决方法)?

Turns out that this was a documented breaking change in version 4.5:事实证明,这是 4.5 版中记录的重大更改

Restrictions on Assignability to Conditional Types TypeScript no longer allows types to be assignable to conditional types that use infer, or that are distributive.对条件类型可分配性的限制 TypeScript 不再允许将类型分配给使用推断或分配的条件类型。 Doing so previously often ended up causing major performance issues.以前这样做通常会导致主要的性能问题。 For more information, see the specific change on GitHub.更多信息请参见 GitHub 上的具体更改。

So we really need the more verbose version as mentioned in Stonehearts answer所以我们真的需要Stonehearts answer中提到的更详细的版本

Quite verbose since you have to repeat the condition, but it would suppress the error.非常冗长,因为您必须重复该条件,但它会抑制错误。

type ReturnTypeOfMethod<T, K extends FunctionProperties<T>> =
  T[K] extends (...args: any) => any ? ReturnType<T[K]> : never;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM