【问题标题】:Typescript function type assignment issue打字稿函数类型分配问题
【发布时间】:2018-10-11 12:49:49
【问题描述】:

我正在尝试在我的应用程序中使用 json-rpc-ws 库,但我遇到了由库定义的处理程序函数签名问题。

该库在声明文件中具有以下类型别名(连接是一个接口):

export type Handler<TConnection extends Connection, ParamType, ParamCallbackType> = (this: TConnection, params: ParamType, reply: ReplyCallback<ParamCallbackType>) => void;
export type ReplyCallback<ParamType> = (error: any, params?: ParamType) => void;

现在我正在尝试通过以下方式在测试代码中创建处理函数:

// Define a function
const func = (conn: Connection, params: IMyRequest, reply: ReplyCallback<IMyResponse> ) => { }

// Try cast to a handler
const handlerFunc = func as Handler<Connection, IMyRequest, IMyResponse>;

但是我收到一个错误,func 无法转换为相应的类型。我在这里缺少什么?

如果有什么不同,我正在使用 Typescript 2.8.1。

【问题讨论】:

  • 请提供完整的错误信息。
  • [ts] Type '(conn: Connection, params: IMyRequest, reply: ReplyCallback&lt;IMyResponse&gt;) =&gt; void' cannot be converted to type 'Handler&lt;Connection, IMyRequest, IMyResponse&gt;'.

标签: typescript


【解决方案1】:

好的,我想我明白了。在库的定义文件中,this 被键入为连接的继承类型,这是因为在此上下文中调用了处理函数。但是我不需要在我的处理函数中显式提供该参数(因为它已经为this 定义了)。

我的函数的正确签名是:

const func = (params: IMyRequest, reply: ReplyCallback<IMyResponse> ) => { }

【讨论】:

  • 没错。这意味着该函数将在 Connection 对象的上下文中调用。
猜你喜欢
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 2020-06-29
  • 2020-08-27
  • 2016-10-25
  • 1970-01-01
  • 2021-03-17
  • 2022-01-12
相关资源
最近更新 更多