使用 "identical signature" 的 Typescript 方法重载
Typescript Method overload with "identical signature"
考虑这段代码:
class Socket extends EventEmitter {
...
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "connect", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
...
}
来自 typescript / node.js 类型定义文件中的模块“dgram”,这是来自 node.js 的“the”udp 服务器。代码在“dgram.d.ts”文件中。
当我写Socket.on(" in Visual Studio的代码来使用它时,它解析这个方法的第一个参数为:close,connect,error,listening,message,好像它将是一个枚举。
我什至无法为这个“机制”命名正确的术语,这是什么?通常在参数中,它的左侧是变量名,右侧是类型示例(事件:字符串)。但这里看起来文字字符串又是一个有效类型,而且它非常聪明,可以在重载示例中解析它(事件:“关闭”)
如果我在一个简单的单一函数中使用类似 myparameter:"myliteralString" 的东西,它甚至没有意义,据我所知,它只有与重载结合使用才有意义。
如果你能给我说出概念或幕后发生的事情(比如隐式构建数组或类似的东西,这使这项工作成功。我很高兴,我只是想了解它。
感谢您的宝贵时间!
你指的是 Overload Signature 吗?
也许事件的类型是这样定义的:
考虑这段代码:
class Socket extends EventEmitter {
...
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "connect", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
...
}
来自 typescript / node.js 类型定义文件中的模块“dgram”,这是来自 node.js 的“the”udp 服务器。代码在“dgram.d.ts”文件中。
当我写Socket.on(" in Visual Studio的代码来使用它时,它解析这个方法的第一个参数为:close,connect,error,listening,message,好像它将是一个枚举。
我什至无法为这个“机制”命名正确的术语,这是什么?通常在参数中,它的左侧是变量名,右侧是类型示例(事件:字符串)。但这里看起来文字字符串又是一个有效类型,而且它非常聪明,可以在重载示例中解析它(事件:“关闭”) 如果我在一个简单的单一函数中使用类似 myparameter:"myliteralString" 的东西,它甚至没有意义,据我所知,它只有与重载结合使用才有意义。
如果你能给我说出概念或幕后发生的事情(比如隐式构建数组或类似的东西,这使这项工作成功。我很高兴,我只是想了解它。
感谢您的宝贵时间!
你指的是 Overload Signature 吗?
也许事件的类型是这样定义的: