ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
474 stars 57 forks source link

type-challenges-solutions/en/medium-capitalize #80

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

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

hpr commented 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}` : ''
ghaiklor commented 3 years ago

@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).

zhaoyao91 commented 1 year ago

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
albert-luta commented 1 year ago

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}`
  : "";
daniel-hyun-chae commented 1 year ago

Does anyone know how and why '${infer First}' infer only the first character?