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
FirstCharthat takes a generic type parameterTthat extends thestringtype. - We use conditional types to check if
Tmatches 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 returnneverto indicate that the input is invalid.