【问题标题】:Get only methods of an object with a condition on return type仅获取具有返回类型条件的对象的方法
【发布时间】:2021-05-20 22:58:17
【问题描述】:

一开始我有一个带有属性和方法的类。我想过滤以获取方法的键

我为此做了一个实用程序类型,它运行良好:

type FunctionPropertyNames<T> = {
  [K in keyof T]: T[K] extends (...args: any) => any ? K : never;
}[keyof T];

export type OnlyFunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;

现在我只想获取 返回可按字符串索引的结果的方法的键,更准确地说,它们具有 body 属性。我想要这个,因为我想用这个返回类型编写以下函数。

public async call<K extends keyof OnlyFunctionProperties<T>>(
    method: K,
    ...params: Parameters<T[K]>
  ): Promise<ReturnType<T[K]>['body']> {
    const response = {};
    return response as any;
  }

我目前收到以下错误:

类型 '"body"' 不能用于索引类型 'ReturnType'

我尝试修改 FunctionPropertyNames 实用程序,但目前没有解决方案。这是代表问题的ts playground

【问题讨论】:

  • 只是注意到一个可以被body 索引的类型并不意味着它可以被string 索引...看起来你想要一个带有body 属性的东西,而你没有'真的不在乎它是否可以被string 索引。因此,您可能根本不想在问题中提及“可按字符串索引”。

标签: typescript


【解决方案1】:

好吧,ReturnType&lt;T[K]&gt; 将是某种Promise,而Promises 往往没有body 属性。您将需要 conditional type inference 之类的东西来将 body 属性从 Promised 类型中提取出来。也许像:

  public async call<K extends keyof OnlyFunctionProperties<T>>(
    method: K,
    ...params: Parameters<T[K]>
  ): Promise<T[K] extends (...a: any) => Promise<{ body: infer B }> ? B : never>;    

您可以验证它是否有效:

declare const o: OMSApiService<{
  foo: string,
  bar(x: string): number,
  baz(x: string): Promise<string>,
  qux(x: string): Promise<{ body: string, soul: number }>
}>
o.call("qux", "123").then(x => x.toUpperCase()); // okay

Playground link to code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多