[英]Generic TypeScript Type for functions returning functions that replaces the ReturnType with the ReturnType of the returned function
[英]TypeScript: ReturnType -> How to set the return type of function returned by a function
我正在使用 graphql 代码生成器为我的 GraphQL 代码库生成类型。 生成的核心 sdk 的示例代码如下所示
export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {
return {
myCustomFunction(...): Promise<MyFuncReturn>
}
}
getSdk 返回我为 GraphQL 服务器定义的所有 API 的 object。
我正在尝试使用 ReturnType 语法来匹配 myCustomFunction 的返回值,即 MyFuncReturn 在代码的其他部分。 原因是,我的许多查询 / output 响应对象不完整(我不想要所有查询的所有字段),因此我无法将其转换为架构中定义的完整响应 object。
我想利用 ReturnType 以便我的代码的其他部分可以只利用 function 的返回类型,而不是知道正在返回什么 object / 类型,例如:
mytestCode {
callCoreSdk(): ReturnType<getSdk().myCustomFunc>
}
这是可能的和允许的。 尝试了上述并得到错误。 此外,找不到可以在 func 中将 ReturnType 用于 func 的示例。
你的语法有点不对劲,但可以做到。 要获取getSdk
的类型,您需要使用typeof
运算符 ( typeof getSdk
)。 然后可以使用 ReturnType 获取ReturnType
的返回类型( ReturnType<typeof getSdk
ReturnType<typeof getSdk>
)。 要获取返回类型中属性的类型,您可以使用索引类型查询( 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()("")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.