yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

0003-easy-tuple-to-object #3

Open yunliuyan opened 11 months ago

yunliuyan commented 11 months ago

元组转换为对象 简单

by sinoon @sinoon

接受挑战    English 日本語 한국어

欢迎 PR 改进翻译质量。

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

例如:

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

测试案例:

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

返回首页 分享你的解答 查看解答

相关挑战

10・元组转合集 472・Tuple to Enum Object 730・Union to Tuple 3188・Tuple to Nested Object
yunliuyan commented 11 months ago

思路

将元组的元素值提取出来,赋给对象的key和value值。

代码实现

type TupleToObject<T extends readonly any[]> = {
  [key in T[number]]: key
}

注意

Janice-Fan commented 11 months ago

type TupleToObject<T extends ReadonlyArray> = {

}

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const

type result = TupleToObject // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}

wudu8 commented 11 months ago
// 你的答案 
// 不应该使用any[],因为作为键,是不能使用引用类型的,这里应该约束元素里的类型仅能
// 为 string symbol number这三个可以为对象键的类型
type TupleToObject<T extends readonly (string | symbol | number)[]> = {
  [P in T[number]]: P
}

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 error = TupleToObject<[[1, 2], {}]> // Error: Type '[[1, 2], {}]' does not satisfy the constraint 'readonly (string | number | symbol)[]'

type tupleTest = TupleToObject<typeof tuple>; // Ok: { tesla: "tesla"; "model 3": "model 3"; "model X": "model X"; "model Y": "model Y"; }
type tupleNumberTest = TupleToObject<typeof tupleNumber>; // Ok: { 1: 1; 2: 2; 3: 3; 4: 4; }
type tupleMixTest = TupleToObject<typeof tupleMix>; // Ok: { 1: 1; 3: 3; 2: "2"; 4: "4"; }
Naparte commented 11 months ago

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

type TupleToObject<T extends readonly any[]> = {
    [key in T[number]]: key
}

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const

type t3 = typeof tuple;

type result = TupleToObject<typeof tuple> // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}