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
View on GitHubts
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
/* _____________ Your Code Here _____________ */typeTupleToNestedObject <T ,U > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
take the challengets
/* _____________ Your Code Here _____________ */typeTupleToNestedObject <T ,U > = any/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>,]
解决方案
Spoiler warning // Click to reveal answer
ts
// most populartypeTupleToNestedObject <T ,U > =T extends [inferF ,...inferR ]?{[K inF &string]:TupleToNestedObject <R ,U >}:U
ts
// most populartypeTupleToNestedObject <T ,U > =T extends [inferF ,...inferR ]?{[K inF &string]:TupleToNestedObject <R ,U >}:U