타입 챌린지 116 - Replace

소파의 벨로그·2025년 3월 17일

타입챌린지

목록 보기
26/131

문제 링크

문제

문자열 S에서 From를 찾아 한 번만 To로 교체하는 Replace<S, From, To>를 구현하세요.

내 풀이

type Replace<S extends string, From extends string, To extends string> = 
  From extends ''?
    S
    :S extends `${infer Start}${From}${infer Last}`?
      `${Start}${To}${Last}`
      :S

From이 빈 값일 경우 start에 첫 글자 이후에 값이 들어가게 되어 From이 빈 값일 때의 분기처리를 해줬다

다른 사람의 풀이

type Replace<S extends string, From extends string, To extends string> =
  S extends `${infer L}${From extends '' ? never : From}${infer R}`
  ? `${L}${To}${R}`
  : S

이런 식으로 분기처리를 할 수 있었다

참고자료

https://github.com/type-challenges/type-challenges/issues/26593

0개의 댓글