最近在学习vue3的源码,顺便也在学习ts,就记录一下自己学习中的困惑吧
export const isArray = Array.isArray
export const isMap = (val: unknown): val is Map<any, any> =>
toTypeString(val) === '[object Map]'
export const isSet = (val: unknown): val is Set<any> =>
toTypeString(val) === '[object Set]'
export const isDate = (val: unknown): val is Date => toTypeString(val) === '[object Date]'
export const isFunction = (val: unknown): val is Function =>
typeof val === 'function'
export const isString = (val: unknown): val is string => typeof val === 'string'
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
export const isObject = (val: unknown): val is Record<any, any> =>
val !== null && typeof val === 'object'
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
is
,官方解释:是一种类型推断表达式的关键字, 通过和函数返回值的比较, 从而"缩小"参数的类型范围一般会用在类型判断的函数中,类似上面这些,isArray 、 isObject
等,基本都是以isxxx
开头的函数,
export const isString = (val: unknown): val is string => typeof val === 'string'
函数的返回值类型为val is string
,isString返回值为true
的时候, 参数val
就是string
类型
返回值类型为什么不能直接写成boolean?
let str: string | null = Math.random() > 0.1 ? 'str' : null
if (isString(str)) {
str.split()
}
因为如果写成这样,ts无法推测str是否有split方法,str也可能为null,就会报错
感谢知乎一大哥指点迷经,特此记录该文,点击跳转