cosmos
Cosmos
search
blog Hello comment
{ "articleTitle": "实现Tuple2Obj & Length", "date": "2022-10-7 0:16:45", "tags": [ "typescript", "Tuple2Obj" ], "categories": "ts", "timestamp": 1665101805000, "readingTime": 2, "outline": "ts类型体操,实现元组转化为对象以及获取元组长度" }
readingTime: 2min

实现Tuple2Obj

传入一个元组类型,将这个元组类型转换为对象类型,这个对象类型的键/值都是从元组中遍历出来。

例如:

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

实现Tuple2Obj

创建一个通用的Length,接受一个readonly的数组,返回这个数组的长度。

例如:

type tesla = ['tesla', 'model 3', 'model X', 'model Y']
type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT']

type teslaLength = Length<tesla> // expected 4
type spaceXLength = Length<spaceX> // expected 5

遍历数组

T[number] 表示数组中的每一项

T[0] 表示数组第一项

数组长度

T['length'] 表示数组的长度

readonly 范围

仅允许对数组和元组文本类型使用 "readonly" 类型修饰符。ts(1354)

联合类型元组

(string | number | symbol)[]

answer

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

answer2

type Length<T extends readonly (string | number | symbol)[]> = T['length']
Edit on Github