This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
16. implement FirstChar<T>
type FirstChar<T extends string> = T extends `${infer U}${string}` ? U : never;
Explanation:
- We define a type
FirstChar
that takes a generic type parameterT
that extends thestring
type. - We use conditional types to check if
T
matches the pattern of having a first character followed by any number of characters. We use template literal types to achieve this, where${infer U}
captures the first character and${string}
captures the rest of the string. - If it matches the pattern, we return the captured first character
U
. Otherwise, we returnnever
to indicate that the input is invalid.