繁体   English   中英

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

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

在 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]>;

参见Playground 4.4.4 示例

但是相同的代码无法在 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'.

奇怪的是ReturnTypeNumber类型仍然显示预期的类型(本例中为number )。
知道为什么这不再起作用或如何解决此问题(使用@ts-ignore不是解决方法)?

事实证明,这是 4.5 版中记录的重大更改

对条件类型可分配性的限制 TypeScript 不再允许将类型分配给使用推断或分配的条件类型。 以前这样做通常会导致主要的性能问题。 更多信息请参见 GitHub 上的具体更改。

所以我们真的需要Stonehearts answer中提到的更详细的版本

非常冗长,因为您必须重复该条件,但它会抑制错误。

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