【问题标题】:TypeScript: ReturnType -> How to set the return type of function returned by a functionTypeScript: ReturnType -> 如何设置函数返回的函数的返回类型
【发布时间】:2020-08-31 21:09:59
【问题描述】:

我正在使用 graphql codegen 为我的 GraphQL 代码库生成类型。生成的核心 sdk 的示例代码如下所示

export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {
  return {
   myCustomFunction(...): Promise<MyFuncReturn>
 }
}

getSdk 返回我为我的 GraphQL 服务器定义的所有 API 的对象。

我正在尝试使用 ReturnType 语法来匹配 myCustomFunction 的返回值,即代码其他部分中的 MyFuncReturn。原因是,我的许多查询/输出响应对象都不完整(我不想要所有查询的所有字段),因此我无法将其类型转换为模式中定义的完整响应对象。

我想利用 ReturnType,这样我的代码的其他部分就可以利用函数的返回类型,而不是知道返回的是什么对象/类型,例如:

mytestCode {

    callCoreSdk(): ReturnType<getSdk().myCustomFunc>
}

这是可能的和允许的。尝试了上述并得到错误。此外,找不到可以在 func 中使用 ReturnType 的示例。

【问题讨论】:

    标签: typescript graphql


    【解决方案1】:

    您的语法有点偏离,但可以做到。要获得getSdk 的类型,您需要使用typeof 运算符(typeof getSdk)。然后可以使用ReturnType获取getSdk的返回类型(ReturnType&lt;typeof getSdk&gt;)。要在返回类型中获取属性的类型,您可以使用 index type query (ReturnType&lt;typeof getSdk&gt;['myCustomFunction'])

    export function getSdk() {
      return {
        myCustomFunction(a: string): Promise<MyFuncReturn> { return null! }
     }
    }
    
    interface mytestCode {
        callCoreSdk(): ReturnType<typeof getSdk>['myCustomFunction']
    }
    
    declare var x: mytestCode;
    x.callCoreSdk()("")
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 2021-05-28
      • 2021-04-01
      • 2023-02-15
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 2021-05-01
      • 2021-01-31
      相关资源
      最近更新 更多