文章摘要

1、在页面关闭时,前端上传监控数据的4个解决方案
https://juejin.cn/post/7106365076197605413

摘要:本文以 “前端监控上报数据” 的业务场景,重点解析在 页面实例关闭 时,如何将监控数据上传到服务端的解决方案。

fetch keepalive

const url = 'http://api.wangxiaokai.vip/test';
const data = JSON.stringify({
      time: performance.now()
    });
    
fetch(url, {
    method: 'POST',
    body: data,
    headers: {
        'Content-Type': 'application/json'
    },
    keepalive: true,
});

 2、TS

https://juejin.cn/post/7088304364078497800

在线运行ts

交叉类型:将多个类型合并为一个类型,使用&符号连接

    type AProps = { a: string }
    type BProps = { b: number }

    type allProps = AProps & BProps

    const Info: allProps = {
        a: '小杜杜',
        b: 7
    }

类型守卫:是可执行运行时检查的一种表达式,用于确保该类型在一定的范围内。

我个人的感觉是,类型守卫就是你可以设置多种类型,但我默认你是什么类型的意思

目前,常有的类型守卫共有4种:in关键字、typeof关键字、instanceof和类型谓词(is)

    interface Info {
      name: string
      age: number
    }

    interface Info1{
      name: string
      flage: true
    }

    const setInfo = (data: Info | Info1) => {
      if("age" in data){
        console.log(`我的名字是:${data.name},年龄是:${data.age}`)
      }

       if("flage" in data){
        console.log(`我的名字是:${data.name},性别是:${data.flage}`)
      }
    }

    setInfo({name: '小杜杜', age: 7}) // "我的名字是:小杜杜,年龄是:7" 
    setInfo({name: '小杜杜', flage: true}) // "我的名字是:小杜杜,性别是:true"

typeof

 

    const setInfo = (data: number | string | undefined) => {
      if(typeof data === "string"){
        console.log(`我的名字是:${data}`)
      }

      if(typeof data === "number"){
        console.log(`我的年龄是:${data}`)
      }

      if(typeof data === "undefined"){
        console.log(data)
      }
    }

    setInfo('小杜杜') // "我的名字是:小杜杜"  
    setInfo(7) // "我的年龄是:7" 
    setInfo(undefined) // undefined" 

 

泛型:

    const calcArray = <T,U>(name:T, age:U): {name:T, age:U} => {
        const res: {name:T, age:U} = {name, age}
        return res
    }

    const res = calcArray<string, number>('小杜杜', 7)
    console.log(res) 

定义了两个类型<T,U>,然后定义了函数的入参类型:(name:T, age:U),返回值的类型{name:T, age:U}

posted @ 2022-06-20 09:40  小猪冒泡  阅读(63)  评论(0编辑  收藏  举报