跳到主要内容

TupleToNested

介绍

一个元素类型都为字符串的元组类型, 递归构建一个对象

ts
type a = TupleToNestedObject<['a'], string> // {a: string}
type b = TupleToNestedObject<['a', 'b'], number> // {a: {b: number}}
type c = TupleToNestedObject<[], boolean> // boolean. if the tuple is empty, just return the U type
ts
type a = TupleToNestedObject<['a'], string> // {a: string}
type b = TupleToNestedObject<['a', 'b'], number> // {a: {b: number}}
type c = TupleToNestedObject<[], boolean> // boolean. if the tuple is empty, just return the U type
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type TupleToNestedObject<T, U> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<TupleToNestedObject<['a'], string>, { a: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToNestedObject<['a', 'b'], number>, { a: { b: number } }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToNestedObject<['a', 'b', 'c'], boolean>, { a: { b: { c: boolean } } }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToNestedObject<[], boolean>, boolean>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
ts
/* _____________ Your Code Here _____________ */
 
type TupleToNestedObject<T, U> = any
 
/* _____________ Test Cases _____________ */
 
type cases = [
Expect<Equal<TupleToNestedObject<['a'], string>, { a: string }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToNestedObject<['a', 'b'], number>, { a: { b: number } }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToNestedObject<['a', 'b', 'c'], boolean>, { a: { b: { c: boolean } } }>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<TupleToNestedObject<[], boolean>, boolean>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// most popular
type TupleToNestedObject<T, U> = T extends [infer F,...infer R]?
{
[K in F&string]:TupleToNestedObject<R,U>
}
:U
 
ts
// most popular
type TupleToNestedObject<T, U> = T extends [infer F,...infer R]?
{
[K in F&string]:TupleToNestedObject<R,U>
}
:U
 
view more solutions