简体   繁体   English

TypeScript: ReturnType -> 如何设置 function 返回的 function 的返回类型

[英]TypeScript: ReturnType -> How to set the return type of function returned by a function

I am using graphql codegen to generate the types for my GraphQL codebase.我正在使用 graphql 代码生成器为我的 GraphQL 代码库生成类型。 A sample code of the core sdk generated looks like this生成的核心 sdk 的示例代码如下所示

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

getSdk returns an object of all the API's I have defined for my GraphQL Server. getSdk 返回我为 GraphQL 服务器定义的所有 API 的 object。

I am trying to use ReturnType syntax to match the return value of myCustomFunction ie MyFuncReturn in other parts of the code.我正在尝试使用 ReturnType 语法来匹配 myCustomFunction 的返回值,即 MyFuncReturn 在代码的其他部分。 Reason being, many of my queries / output response objects are incomplete (I dont want all the fields for all the queries) and hence I cant typecast it to the complete response object defined in the schema.原因是,我的许多查询 / output 响应对象不完整(我不想要所有查询的所有字段),因此我无法将其转换为架构中定义的完整响应 object。

I want to leverage ReturnType to such that my other parts of the code can just leverage the returntype of the function rather than knowing what object / type is being returned, something like:我想利用 ReturnType 以便我的代码的其他部分可以只利用 function 的返回类型,而不是知道正在返回什么 object / 类型,例如:

mytestCode {

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

Is this possible and allowed.这是可能的和允许的。 Tried the above and getting error.尝试了上述并得到错误。 Also, could not locate examples where I can use ReturnType for a func inside a func.此外,找不到可以在 func 中将 ReturnType 用于 func 的示例。

Your syntax is a bit off, but it can be done.你的语法有点不对劲,但可以做到。 To get the type of getSdk you need to use the typeof operator ( typeof getSdk ).要获取getSdk的类型,您需要使用typeof运算符 ( typeof getSdk )。 Then can use ReturnType to get the return type of getSdk ( ReturnType<typeof getSdk> ).然后可以使用 ReturnType 获取ReturnType的返回类型( ReturnType<typeof getSdk ReturnType<typeof getSdk> )。 To get the type of a property in the return type you can use an index type query ( ReturnType<typeof getSdk>['myCustomFunction'] )要获取返回类型中属性的类型,您可以使用索引类型查询ReturnType<typeof getSdk>['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 游乐场链接

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

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