我希望设计一个可以直接调用并具有重载功能的消息函数.然后,我还希望Message函数下还有其他函数调用,比如Message.confirm().这似乎不容易在类型脚本中实现,要编写类型描述,但在编写实现时似乎很难一下子满足所有类型.

我试图定义一个类,但在调用该类时,它提示必须使用new关键字.我试着直接定义一个函数,但它不能满足函数的性质.这必须一步一步地完成.

例如,让我定义下面的类,它将提示您必须使用new来调用

class message {
    message(msg: string): any
    message(msg: string, type: string): any
    message(msg: string, type?: string){

    }

    static confirm(){

    }
}

message("123")

我对使用以下定义还有另一个问题:

type Message = {
    message(msg: string): any
    message(msg: string, type: string): any
    confirm(): any
}

const message: Message = function message (msg: string, type?: string)
    {
    }

message.confirm = function(){}

最后一个问题是,我如何定义和实现消息函数?

推荐答案

如果您希望能够将Message视为一个函数,那么它应该有call signatures个而不是名为message()的方法:

type Message = {
  (msg: string): any // <-- call signature, not method
  (msg: string, type: string): any // <-- call signature, not method
  confirm(): any
}

然后,您的示例代码应该开始按原样工作,因为它支持property declarations on functions:

const message: Message = function message(msg: string, type?: string) {
}

message.confirm = function () { }

Playground link to code

Typescript相关问答推荐

如何将http上下文附加到angular中翻译模块发送的请求

如何根据数据类型动态注入组件?

typescript抱怨值可以是未定义的,尽管类型没有定义

如何使用函数填充对象?

获取函数中具有动态泛型的函数的参数

如何将泛型对象作为返回类型添加到类型脚本中

有没有可能产生输出T,它在视觉上省略了T中的一些键?

创建Angular 为17的动态形状时出错

在TypeScript中扩展重载方法时出现问题

当数组类型被扩展并提供标准数组时,TypeScrip不会抱怨

TypeScrip-如何自动推断UNION变量的类型

使用Cypress测试从Reaction受控列表中删除项目

埃斯林特警告危险使用&as";

typescript如何从映射类型推断

Vite+Chrome扩展 list v3-;不能在模块外使用import语句;对于inpage脚本

通过辅助函数获取嵌套属性时保留类型

在类型{}上找不到带有string类型参数的索引签名 - TypeScript

使用 fp-ts 时如何使用 TypeScript 序列化任务执行?

将 Angular 从 14 升级到 16 后出现环境变量注入问题

typeof 运算符和泛型的奇怪行为