typescript 接口定义函数

刚开始用 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}) {}
}
阅读 7.2k
2 个回答

不知道我理解问题还是。。问的不清楚,你要校验的貌似是函数参数,那么与函数本身并无关系,你只要定义好参数的type,调用函数自然会使用对应的校验规则,不管是具名还是匿名函数,参数的类型确定后,都不受影响。
另外,没看出来哪里没有准确校验,方便可以举个错误例子,或者你希望的效果没达到的简单说明。

非要用解构的写法那函数定义的时候还是要重新描述一下解构对象的类型的,目前ts没法自动推导,问题2一样

let message: MeaageFunc
message = function({message,type = 'infosss', title = '提示', duration = 5000}: MessageConfig) {}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题