账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    typescript 接口定义函数
    31
    0

    刚开始用 typescript 有些不懂 请教大家下.

    用接口去定义匿名函数 且 参数不为 结构赋值 这样能够准确校验类型

    type NoticeType = 'error' | 'success' | 'info' | 'warning'
    
    interface MeaageFunc {
     (message: string, type: NoticeType, title: string, duration: number): void
    }
    
    let message: MeaageFunc
    
    message = function(message,type = 'info', title = '提示', duration = 5000) {}
    

    问题1
    如果我用 结构赋值 下面的写法 不会校验参数 type 的类型 怎么修改

    type NoticeType = 'error' | 'success' | 'info' | 'warning'
    
    interface MessageConfig {
      message: string
      type?: NoticeType
      title?: string
      duration?: number
    }
    
    interface MeaageFunc {
     ({message, type, title, duration}: MessageConfig): void
    }
    let message: MeaageFunc
    message = function({message,type = 'infosss', title = '提示', duration = 5000}) {}

    问题2 如果我定义一个接口 里面有多个具名函数 下面的写法不能准确的参数 type 的校验 要怎么修改呢

     interface NoticeConfig {
      message:({message, type, title, duration}: MessageConfig) => void
      notify:({message, type, title, duration}: MessageConfig) => void
    }
    
    const Notice: NoticeConfig = {
        message({message,type = 'infoasas', title = '提示', duration = 5000}) {}
    }
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • ︶ㄣ随гゞ枫 普通会员 1楼

      在 TypeScript 中,接口是一个包含一组类型和方法的蓝图,它定义了函数的类型和行为。接口可以用于表示类的抽象,帮助你定义可复用的代码块。

      例如,假设你有一个名为 Person 的接口,它有以下方法:

      typescript interface Person { name: string; age: number; }

      然后,你可以定义一个名为 PersonImpl 的类,它实现了 Person 接口:

      ```typescript class PersonImpl implements Person { name: string; age: number;

      constructor(name: string, age: number) { this.name = name; this.age = age; }

      getAge(): number { return this.age; }

      setName(name: string): void { this.name = name; } } ```

      在这个例子中,PersonImpl 类实现了 Person 接口的所有方法,包括 getAgesetName。你可以像使用任何其他类一样使用它,只需要确保它实现了 Person 接口。

      例如,你可以创建一个新的 PersonImpl 实例,并设置它的名字和年龄:

      typescript const person = new PersonImpl("Alice", 25); console.log(person.getName()); // 输出 "Alice" person.setName("Bob"); console.log(person.getName()); // 输出 "Bob"

      这就是如何在 TypeScript 中定义接口和函数。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部