この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - TypeScript タイプパズル
33. implement TupleToString<T>
解答例:
type TupleToString<T extends string[]> = T extends [infer Head, ...infer Tail] ? Head extends string ? `${Head}${TupleToString<Tail>}` : never : '';
Explanation:
TupleToString<T extends string[]>
defines a generic type T that extends an array of strings.T extends [infer Head, ...infer Tail]
deconstructs the tuple by getting its first element asHead
and the rest asTail
.Head extends string ? ... : never
is a conditional type that checks whetherHead
is a string.${Head}${TupleToString<Tail>}
concatenatesHead
with the result of the recursive call ofTupleToString
on the rest of the tuple elements,Tail
.: '';
specifies the base case of an empty tuple, which returns an empty string.
Note that the use of infer
allows us to capture the type of Tail
in each iteration of the recursive call, which ensures that the returned type is a string.