본문 바로가기
Language/Typescript

타입챌린지 : 106-Trim Left (medium)

by hsloth 2023. 3. 27.

 

이 글은 제가 타입챌린지를 하면서 해석한 내용을 적는 글입니다. 틀린 내용이 있으면 댓글 달아주시면 감사하겠습니다.

 

https://github.com/type-challenges/type-challenges/blob/main/questions/00106-medium-trimleft/README.md

 

GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge

Collection of TypeScript type challenges with online judge - GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge

github.com

 

TrimLeft는 문자열을 제네릭 인자로 넣어주었을 때, 해당 문자열의 왼쪽 공백을 제거하는 타입이다.

 

type TrimLeft<S extends string> = S extends `${" " | "\n" | "\t"}${infer O}` ? TrimLeft<O> : S;

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<TrimLeft<'str'>, 'str'>>,
  Expect<Equal<TrimLeft<' str'>, 'str'>>,
  Expect<Equal<TrimLeft<'     str'>, 'str'>>,
  Expect<Equal<TrimLeft<'     str     '>, 'str     '>>,
  Expect<Equal<TrimLeft<'   \n\t foo bar '>, 'foo bar '>>,
  Expect<Equal<TrimLeft<''>, ''>>,
  Expect<Equal<TrimLeft<' \n\t'>, ''>>,
]

 

 

 

내가 처음 적었던 답을 봐보자.

실수로 왼쪽만 Trim한 것이 아니라 전체 공백을 지우는 코드로 작성을 해버린 코드이다.

type TrimLeft<S extends string> = {
  [K in keyof S]: S[K] extends " " ? never : S[K];
}

자바스크립트에서 string은 배열로 취급할 수 있다. 그리고 배열은 프로퍼티가 0, 1, 2 ... 인 객체로 취급할 수 있기 때문에 다음과 같이 코드를 작성해 보았다.

결론은... 음... 동작하지 않는다(공백이 제거되지 않는다). string을 객체로 취급하면 key값을 가져오는데 문제가 생기는 걸까...? 어떤식으로 동작하는지는 잘 모르겠다. 

이유를 아시는 분 있으시면 댓글좀 부탁드립니다 ㅠ

 

 

type TrimLeft<S extends string> = S extends `${" " | "\n" | "\t"}${infer O}` 
	? TrimLeft<O> : S;

S extends `${" " | "\n" | "\t"}${infer O}` ? TrimLeft<O> : S; : S를 공백+나머지 로 나누어 공백이 나오지 않을 때 까지 TrimLeft를 하여 공백을 없애주는 코드이다.

 

 

 

'Language > Typescript' 카테고리의 다른 글

타입챌린지 : 110-Capitalize (medium)  (0) 2023.03.29
타입챌린지 : 108-Trim (medium)  (0) 2023.03.28
타입챌린지 : 62-Type Lookup  (0) 2023.03.24
타입챌린지 : 20-Promise.all  (0) 2023.03.24
타입챌린지 : 16-Pop (medium)  (0) 2023.03.22