Skip to content

TupleToNestedObject

约 241 字小于 1 分钟

2022-12-01

题目

Github: TupleToNestedObject

给定一个仅包含字符串类型的元组类型 T ,以及一个类型 U ,递归地构建一个对象。

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

解题思路

略。

答案

type TupleToNestedObject<T, U> = T extends [infer L extends PropertyKey, ...infer O]
  ? { [P in L]: TupleToNestedObject<O, U> }
  : U

验证

type 
cases
= [
Expect
<
Equal
<
TupleToNestedObject
<['a'], string>, {
a
: string }>>,
Expect
<
Equal
<
TupleToNestedObject
<['a', 'b'], number>, {
a
: {
b
: number } }>>,
Expect
<
Equal
<
TupleToNestedObject
<['a', 'b', 'c'], boolean>, {
a
: {
b
: {
c
: boolean } } }>>,
Expect
<
Equal
<
TupleToNestedObject
<[], boolean>, boolean>>,
]

参考