Typescript类型体操 - TupleToNestedObject
题目
中文
给定一个只包含字符串类型的元组类型T
和一个类型 U
, 递归地构建一个对象.
English
Given a tuple type T
that only contains string type, and a type U
, build an object recursively.
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 extends string[], U> = T extends [
infer L extends string,
...infer R extends string[]
]
? { [k in L]: R extends [] ? U : TupleToNestedObject<R, U> }
: U;
作者:Laggage
出处:https://www.cnblogs.com/laggage/p/type-challenge-tuple-to-nested-object.html
说明:转载请注明来源