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