• [Typescript Challenges] 3. Easy Tuple to Object


    For example:

    const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
    
    type result = TupleToObject<typeof tuple> // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}
    
    /* _____________ Your Code Here _____________ */
    
    type TupleToObject<T extends ReadonlyArray<string | number>> = {
      [Key in T[number]]: Key
    }
    
    
    /* _____________ Test Cases _____________ */
    import type { Equal, Expect } from '@type-challenges/utils'
    
    const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
    const tupleNumber = [1, 2, 3, 4] as const
    const tupleMix = [1, '2', 3, '4'] as const
    
    type cases = [
      Expect<Equal<TupleToObject<typeof tuple>, { tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y' }>>,
      Expect<Equal<TupleToObject<typeof tupleNumber>, { 1: 1; 2: 2; 3: 3; 4: 4 }>>,
      Expect<Equal<TupleToObject<typeof tupleMix>, { 1: 1; '2': '2'; 3: 3; '4': '4' }>>,
    ]
    
    1. Have to use as const, if not, typeof tuple will be string[], with as const, then typeof tuple is ['tesla', 'model 3', 'model X', 'model Y']
    2. T[number] helps to loop over the array in sequence.
  • 相关阅读:
    FileWriter简单用法并记录日志
    jquery 替换元素函数
    jquery ajax应用
    jquery 操作对象和集合
    jquery 管理包装元素集合
    jQuery 过滤选择器
    @Html.Action()
    ASP.NET MVC之Html.RenderAction
    MVC5中路由新特性
    MVC5学习整理
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16643379.html
Copyright © 2020-2023  润新知