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   ChoZ  阅读(1)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示