我有以下功能:
const ServerRequest = ({ token: ServerRequestOptions }) => ({
async() {}
})
而且我无法将 ServerRequest
用作我的 AuthService
上的直接类型,因为它是一个函数,所以我必须做一些“技巧”,比如:
const AuthService = (request: ReturnType<typeof ServerRequest>) => ({ })
对我来说,这个技巧听起来不太好,因为要使用对 ServerRequest 的简单引用,我必须组合一些“复杂”类型。我还尝试将其导出为差异类型:
type ServerRequestType = ReturnType<typeof ServerRequest>
但我看到许多命名约定说“永远不要”使用前缀/后缀,如 I
、Interface
、Type
等。
那么,对于这种情况,最佳路径应该是什么?
最佳答案
您只需要定义函数签名的类型。
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
函数上)。
关于 typescript :如何为返回文字对象的工厂函数定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57843230/