Implement `Capitalize<T>` which converts the first letter of a string to uppercase and leave the rest as-is. Master TypeScript template literal types in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement Capitalize<T> which converts the first letter of a string to uppercase and leave the rest as-is.
Implement Capitalize<T> which converts the first letter of a string to uppercase and leave the rest as-is.
For example
[object Object]Change the following code to make the test cases pass (no type check errors).
// Video Solution: https://youtube.com/watch?v=fWDkk8Y2P2k
/* _____________ Your Code Here _____________ */
type MyCapitalize<S extends string> = any
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'
type cases = [
Expect<Equal<MyCapitalize<'foobar'>, 'Foobar'>>,
Expect<Equal<MyCapitalize<'FOOBAR'>, 'FOOBAR'>>,
Expect<Equal<MyCapitalize<'foo bar'>, 'Foo bar'>>,
Expect<Equal<MyCapitalize<''>, ''>>,
Expect<Equal<MyCapitalize<'a'>, 'A'>>,
Expect<Equal<MyCapitalize<'b'>, 'B'>>,
Expect<Equal<MyCapitalize<'c'>, 'C'>>,
Expect<Equal<MyCapiUnlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type MyCapitalize<S extends string> = S extends `${infer First}${infer Rest}`
? `${Uppercase<First>}${Rest}`
: SHow it works:
S to be a string with extends stringS extends ${infer First}${infer Rest} matches the string type and captures the first letter into First and the rest of the string into Rest? ${Uppercase<First>}${Rest} returns the string with the first letter capitalized: S returns the string if it doesn't start with a letterThis challenge helps you understand TypeScript's template literal types and how to apply this concept in real-world scenarios.
This challenge is originally from here.