Typescript:如何为返回文字对象的工厂函数定义类型

Typescript:如何为返回文字对象的工厂函数定义类型,typescript,typescript-typings,Typescript,Typescript Typings,我有以下功能: const ServerRequest = ({ token: ServerRequestOptions }) => ({ async() {} }) 我不能在我的AuthService上直接使用ServerRequest作为类型,因为它是一个函数,所以我必须做一些“技巧”,比如: constauthservice=(请求:ReturnType)=>({}) 对我来说,这个技巧听起来并不好,因为要使用对ServerRequest的简单引用,我必须编写一些“复杂”类型

我有以下功能:

const ServerRequest = ({ token: ServerRequestOptions }) => ({
  async() {}
})
我不能在我的
AuthService
上直接使用
ServerRequest
作为类型,因为它是一个函数,所以我必须做一些“技巧”,比如:

constauthservice=(请求:ReturnType)=>({})
对我来说,这个技巧听起来并不好,因为要使用对ServerRequest的简单引用,我必须编写一些“复杂”类型。我还尝试将其导出为差异类型:

type ServerRequestType = ReturnType<typeof ServerRequest>
type ServerRequestType=ReturnType
但我看到许多命名约定都说“从不”使用前缀/后缀,比如
I
接口
类型
,等等


那么,对于这种情况,最好的路径应该是什么呢?

您只需要定义函数签名的类型

接口服务器请求选项{/*…*/}
//真函数签名
键入ServerRequestFunc=(选项:{token:ServerRequestOptions})=>void;
//可变保持函数
const serverRequest:ServerRequestFunc=({token:ServerRequestOptions})=>({
异步(){}
})
const authService=(请求:ServerRequestFunc)=>({})
authService(服务器请求);//很好。
或者更简单,如果我们将名称添加到输入参数
serverRequest

constserverrequest=(选项:{token:string})=>({
异步(){}
})
const authService=(请求:typeof serverRequest)=>({})
authService(服务器请求);//也有效

仅在第二个示例中,intellisense并不漂亮(例如:将鼠标悬停在IDE中的
authService
函数上)。

我建议
ServerRequest
不是工厂函数的合适名称,它应该是
makeServerRequest
或类似名称。然后,您可以为它返回的内容定义一个类型(可能是
ServerRequest
:-),并在必要时使用该类型。
type ServerRequestType = ReturnType<typeof ServerRequest>