美文网首页
对象 key 值扩展

对象 key 值扩展

作者: sweetBoy_9126 | 来源:发表于2023-02-05 14:41 被阅读0次
    import type { Equal, Expect } from '@type-challenges/utils'
    
    type test1 = {
      key: 'cat'
      value: 'green'
    }
    
    type testExpect1 = {
      key: 'cat'
      value: 'green'
      home: boolean
    }
    
    type test2 = {
      key: 'dog' | undefined
      value: 'white'
      sun: true
    }
    
    type testExpect2 = {
      key: 'dog' | undefined
      value: 'white'
      sun: true
      home: 1
    }
    
    type test3 = {
      key: 'cow'
      value: 'yellow'
      sun: false
    }
    
    type testExpect3 = {
      key: 'cow'
      value: 'yellow'
      sun: false
      isMotherRussia: false | undefined
    }
    
    type cases = [
      Expect<Equal<AppendToObject<test1, 'home', boolean>, testExpect1>>,
      Expect<Equal<AppendToObject<test2, 'home', 1>, testExpect2>>,
      Expect<Equal<AppendToObject<test3, 'isMotherRussia', false | undefined>, testExpect3>>,
    ]
    
    
    type AppendToObject<T extends object, U extends string, V> = {
      [k in keyof T | U]: k extends keyof T ? T[k] : V
    }
    

    获取一个对象字面量类型的 value 值

    const RestfulMethod = {
      get: 'GET',
      post: 'POST',
      put: 'PUT',
      delete: 'DELETE'
    } as const
    
    
    type IRestfulMethod = typeof RestfulMethod
    type TypeRestfulMethod = IRestfulMethod[keyof IRestfulMethod] // GET | POST | PUT | DELETE
    

    相关文章

      网友评论

          本文标题:对象 key 值扩展

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