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

标签 typescript typescript-typings

我有以下功能:

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

而且我无法将 ServerRequest 用作我的 AuthService 上的直接类型,因为它是一个函数,所以我必须做一些“技巧”,比如:

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

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

type ServerRequestType = ReturnType<typeof ServerRequest>

但我看到许多命名约定说“永远不要”使用前缀/后缀,如 IInterfaceType 等。

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

最佳答案

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

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/

相关文章:

Typescript 接口(interface) : Not all constituents of type 'string | (() => string)' are callable. 类型 'string' 没有调用签名

angular - TypeError : Cannot add property 1, 对象在 Array.push (<anonymous>) 处不可扩展↵

javascript - 如何在动态加载的 Typescript 中扩展类

javascript - 使用类原型(prototype)键入 : Type declaration for JS module exporting instance of class,

javascript - Import'd React.Component 不使用 Typescript 渲染

typescript - controller.ts(8,8) : error TS2339: Property 'user' does not exist on type 'Request' while extending express. 请求

javascript - typescript 中映射的定义列表中的动态键名称

javascript - 我应该在 typeScript 中为我的 json 数据定义类型吗?

javascript - 实例化子对象(对象内的对象)Angular 2

angular - 在 Angular 中创建新日期时删除时区信息