typeof

作者: sweetBoy_9126 | 来源:发表于2022-07-24 10:26 被阅读0次
    1. 对于对象
      如果对象嵌套层级比较深,我们手动定义ts类型会很复杂
    const lo = {
      name: 'ff',
      age: 18,
      address: {
        province: '中国'
      }
    }
    
    type Person = typeof lo
    等价于 
    type Person = {
      name: string
      age: number
      address: {
        province: string
      }
    }
    
    1. 配合 keyof 获取所有枚举属性名
    enum HttpMethod {
         Get,
         Post
     }
     const method: typeof HttpMethod = {
         Get: 0,
         Post: 1,
     }
     type Method = keyof typeof HttpMethod
     // "Get"  | "Post"
    
    1. 获取函数的类型
    function add(a: number, b: number) {
      return a + b
    }
    type AddType = typeof add // (a: number, b: number) => number
    
    // 获取函数返回值类型
    type AddReturnType = ReturnType<AddType> // number
    
    // 获取函数参数类型
    type AddParamsType = Parameters<AddType> // [a: number, b: number]
    
    1. 配合 as const 获取更精确的类型
    let user = {
      id: 666,
      name: "发发"
    } as const
    type User = typeof user 
    // {readonly id: 666, readonly name: '发发'}
    

    相关文章

      网友评论

          本文标题:typeof

          本文链接:https://www.haomeiwen.com/subject/maqiirtx.html