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;

在线演示

posted @ 2022-09-22 21:31  Laggage  阅读(36)  评论(0编辑  收藏  举报