この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - TypeScript タイプパズル
52. implement Split<S, D>
type Split<S extends string, D extends string> = S extends `${infer L}${D}${infer R}` ? [L, ...Split<R, D>] : [S];
Explanation:
- We start by defining a generic type
Split<S, D>
whereS
is the input string andD
is the delimiter to split the string with. - We use conditional type checking to check if the input string contains the delimiter. If it does, we split the string into two parts, separated by the delimiter. We use the
infer
keyword to extract the first part of the string, denoted byL
. - We then recursively call
Split<R, D>
on the second part of the string, denoted byR
. We use the spread operator...
to concatenateL
and the result of the recursive Split call. - If the input string does not contain the delimiter, we simply return an array with the input string as the only element.
Note: We could have also used string
instead of S
and D
to allow for any string input, but using generics provides better type safety.