• [Typescript] 98. Medium Append to object


    Implement a type that adds a new field to the interface. The type takes the three arguments. The output should be an object with the new field.

    For example

    type Test = { id: '1' }
    type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }
    /* _____________ Your Code Here _____________ */
    type Merge<T extends Record<PropertyKey, any>> = {
      [Key in keyof T]: T[Key]
    } 
    type AppendToObject<T extends Record<PropertyKey, any>, U extends string | number | symbol, V extends any> = Merge<T & {
      [Key in U]: V  
    }>
    
    /* _____________ Test Cases _____________ */
    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>>,
    ]
  • 相关阅读:
    视频直播思路
    Swift 算法实战之路:栈和队列
    多线程(RunLoop)
    Charle抓包与wireshark使用
    CoreData归纳使用
    支付宝接入心得(流程)
    TableView的性能优化
    app启动页问题
    公司的开发者账号申请
    java关于时间的笔记
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16884174.html
Copyright © 2020-2023  润新知