tuple to object

作者: sweetBoy_9126 | 来源:发表于2022-07-19 22:20 被阅读0次

测试 case

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' }>>,
]

// @ts-expect-error
type error = TupleToObject<[[1, 2], {}]>
  • template.ts
type TupleToObject<T extends readonly any[]> = any

相关知识点

  1. typeof
    使用 let const 声明的 我们称之为 js 世界
    使用 type interface 声明的可以成为 type 世界
    typeof 可以把js世界的东西变成类型世界的东西,参与到类型世界里的计算

  2. as const
    将我们的类型变成写死的字面量类型

const tuple = ['tesla', 'model 3', 'model X', 'model Y']
type r = typeof tuple // string[]
tuple[0] ='xxx'

上面代码不加 as const 我们的 r是string[],因为我们可以对里面的每一项进行修改

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type r = typeof tuple // readonly ["tesla", "model 3", "model X", "model Y"]
tuple[0] ='xxx' // 无法分配到 "0" ,因为它是只读属性

加上 as const 后我们的 r 就变成了只读的字面量类型了,而且里面的每一项都不可以修改都是一个常量

  1. T[number]
    得到数组里的每一项的联合类型
const arr = [1,2,3] as const
type a = typeof arr[number] // 1 | 2 | 3

配合 in 可对齐每一项进行遍历

js 实现

const tupleToObject = (array) => {
  const obj = {}
  array.forEach((val) => {
    obj[val] = val
  })
  return obj
}

步骤

    1. 返回一个对象
    1. 遍历array

ts 实现

// 1. = {}
// 2. [P in T[number]]

type TupleToObject<T extends readonly(string | number | symbol)[]> = {
  [P in T[number]]: P
}

相关文章

  • tuple to object

    测试 case template.ts 相关知识点 typeof使用 let const 声明的 我们称之为 js...

  • python内置函数isinstance的用法

    isinstance说明如下:isinstance(object, class-or-type-or-tuple)...

  • scala tuple

    object ScalaTuple extends App { // scala 的映射与元组(tuple)// ...

  • 001__基础类型

    元组Tuple Any 当你不知道数据类型 这个代表所有 与Object 对比 Object允许赋值任何类型但是不...

  • 搜索引擎的高级技巧

    精确匹配搜索 使用双引号 “”,在搜索框中键入TypeError: 'tuple' object does not...

  • TS1 基本语法

    ts 指令 基本用法 object 函数 数组 元组 tuple(固定长度的数组) 枚举 enum 或 | 与 ...

  • hive sql 中lateral view explode/j

    先贴一下hive中get_json_object和json_tuple两个函数的区别: Hive中提供了两种针对j...

  • 元组

    tuple与list类似,区别在于tuple中的元素无法修改 定义tuple 使用 () 来定义tuple 可以把...

  • Scala 简明速学05 集合-Tuple

    Scala 简明速学05 集合-Tuple Tuple Scala中Tuple为单个键值对。

  • tupletupletuple

    就是这个tuple啊,这个混蛋tuple是不能修改的。 tuple=('曹操','刘备','孙权') print(...

网友评论

    本文标题:tuple to object

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