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

时间:2019-09-08 15:20:50

标签: typescript typescript-typings

我具有以下功能:

const ServerRequest = ({ token: ServerRequestOptions }) => ({
  async() {}
})

并且我无法使用ServerRequest作为我的AuthService上的直接输入,因为它是一个函数,所以,我必须做一些“技巧”:

const AuthService = (request: ReturnType<typeof ServerRequest>) => ({ })

对我来说,这个技巧听起来不太好,因为要使用对ServerRequest的简单引用,我必须编写一些“复杂”类型。我也尝试将其导出为diff类型:

type ServerRequestType = ReturnType<typeof ServerRequest>

但是我看到许多命名约定说“从不”使用前缀IInterfaceType等。

那么,这种情况的最佳路径应该是什么?

1 个答案:

答案 0 :(得分:1)

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

interface ServerRequestOptions {/* ...*/}

// Proper function signature
type ServerRequestFunc = (options: {token: ServerRequestOptions}) => void;

// variable holding function
const serverRequest: ServerRequestFunc = ({ token: ServerRequestOptions }) => ({
  async() {}
})

const authService = (request: ServerRequestFunc ) => ({ })

authService(serverRequest); // works fine.

或更简单的是,如果我们将名称添加到serverRequest的输入参数中:

const serverRequest = (options: { token: string }) => ({
  async() {}
})

const authService = (request: typeof serverRequest) => ({ })

authService(serverRequest); // also works

仅,在第二个示例中,智能感知并不美观(例如:将鼠标悬停在IDE中的authService函数上)。

相关问题