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;

在線演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章