Open utterances-bot opened 3 years ago
my interpretation of this was to use the built-in Uppercase type instead:
type MyCapitalize<S extends string> = S extends `${infer H}${infer T}` ? `${Uppercase<H>}${T}` : ''
@hpr but, if you use built-in for solving the challenge here, it means we could use built-in Capitalize
itself, don't we? 🙂
I don't think it is "fair enough" (just an opinion).
my long verion solution: https://github.com/type-challenges/type-challenges/issues/18854
type TCapitalMap = {
'a': 'A',
'b': 'B',
'c': 'C',
'd': 'D',
'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L',
'm': 'M',
'n': 'N',
'o': 'O',
'p': 'P',
'q': 'Q',
'r': 'R',
's': 'S',
't': 'T',
'u': 'U',
'v': 'V',
'w': 'W',
'x': 'X',
'y': 'Y',
'z': 'Z',
}
type TSmarllLetters = keyof TCapitalMap
type TCapitalLetters = TCapitalMap[TSmarllLetters]
type MyCapitalize<S extends string> = S extends `${infer THead extends TSmarllLetters}${infer TRest}` ? `${TCapitalMap[THead]}${TRest}` : S
My solution was to use a conditional type, instead of a map.
type CapitalLetter<T extends string> = T extends "a"
? "A"
: T extends "b"
? "B"
: T extends "c"
? "C"
: T extends "d"
? "D"
: T extends "e"
? "E"
: T extends "f"
? "F"
: T extends "g"
? "G"
: T extends "h"
? "H"
: T extends "i"
? "I"
: T extends "j"
? "J"
: T extends "k"
? "K"
: T extends "l"
? "L"
: T extends "m"
? "M"
: T extends "n"
? "N"
: T extends "o"
? "O"
: T extends "p"
? "P"
: T extends "q"
? "Q"
: T extends "r"
? "R"
: T extends "s"
? "S"
: T extends "t"
? "T"
: T extends "u"
? "U"
: T extends "v"
? "V"
: T extends "w"
? "W"
: T extends "x"
? "X"
: T extends "y"
? "Y"
: T extends "z"
? "Z"
: T;
type MyCapitalize<S extends string> = S extends `${infer First}${infer Rest}`
? `${CapitalLetter<First>}${Rest}`
: "";
Does anyone know how and why '${infer First}' infer only the first character?
Capitalize
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/medium-capitalize.html