类型守卫

49 阅读1分钟
//类型守卫
// typeof 无法识别数组和对象,都会被识别为object,可以用instanceof判断
const a = 'asd'
console.log(1, typeof a) // string

const b = 12
console.log(2, typeof b) // number

const c = {a: 1, b: 2}
console.log(3, typeof c) // object
console.log(c instanceof Object) // true
console.log(({}).toString.call(c)) //[object Object]

const e = [1, 2, 3]
console.log(4, typeof e) // object
console.log(e instanceof Array) // true

const d = () => 1 == 1
console.log(5, typeof d) // function

// 自定义类型守卫,只能接受布尔值
// 语法规则:参数 is 类型
// 这个函数如果返回true,那么这个参数就是你想要的类型
const isNum = (data: any): data is number => typeof data == 'number';
const isStr = (data: any): data is string => typeof data == 'string';
const isObject = (data: any): data is object => ({}).toString.call(data) == '[object Object]';
const isFunc = (data: any): data is Function => typeof data == 'function';

// 值经过上述类型守卫判断后,就会被推断为对应的数据类型,然后就可以使用对应类型独有的方法
let args
if (isNum(args)) {
    args.toFixed()
}
if (isStr(args)) {
    args.trim()
}
if (isObject(args)) {
    Object.keys(args)
}
if (isFunc(args)) {
    args()
}