typeof、is

// 收缩类型:判断是不是属于某个类型
// 使用typeof只对基础类型有效
// const isNum = (num:any) => typeof num === 'number'
// 使用instanceof可以对引用类型进行区分
const isArrary = (arr:any) => arr instanceof Array

// 自定义守卫:参数 is 类型
// 弥补使用收缩类型函数后,ts仍然识别为any,无法获取代码提示
const isString = (str:string):str is string => typeof str === 'string'
const isNum = (num:any):num is number => typeof num === 'number'

// 写一个函数:作用是判断传入的参数type是否object,如果是则对属性是number保留小数位2位,是string是去除空格,是函数就执行
// 等同于Object.prototype.toString.call
const isObj = (arg:any) => ({}).toString.call(arg) === '[object Object]'
const isFunction = (fn:any):fn is Function => typeof fn === 'function'
function fn(data:any) {  
  if (isObj(data)) {
    let val
    // 不可以使用for in,因为会遍历到原型的属性
    Object.keys(data).forEach(item => {
      val = data[item]
      if (isNum(val)) {
        // 自定义守卫后是由代码提示的
        data[item] = val.toFixed(2)
      } else if (isString(val)) {
        data[item] = val.trim()
      } else if (isFunction(val)) {
        // 这里独立调用,this会指向window
        // val()
        // 需要换到以下的形式调用
        data[item]()
      }
    })
  }
}
const kk = {
  a: 1.57771,
  b: '   11 ',
  c: function() {
    // node环境中this是undefined
    console.log(this.a);
    return this.a
  }
}
fn(kk)
console.log(kk);

 

posted on 2025-02-18 15:26  ChoZ  阅读(6)  评论(0)    收藏  举报

导航