본문 바로가기
Language/Typescript

타입챌린지 : 529-Absolute (medium)

by hsloth 2023. 4. 10.

 

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

 

https://github.com/type-challenges/type-challenges/blob/main/questions/00529-medium-absolute/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

 

제네릭 인자를 받으면, 해당 제네릭 인자에 절대값을 붙여서 string으로 리턴하는 타입이다.

 

어... 생각보다 너무 쉬워서 놀랐다. 그냥 마음 가는대로 막 썼는데 바로 정답이란다...

 

type Absolute<T extends number | string | bigint> = `${T}` extends `-${infer U}` ? 
	`${U}` : `${T}`

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

type cases = [
  Expect<Equal<Absolute<0>, '0'>>,
  Expect<Equal<Absolute<-0>, '0'>>,
  Expect<Equal<Absolute<10>, '10'>>,
  Expect<Equal<Absolute<-5>, '5'>>,
  Expect<Equal<Absolute<'0'>, '0'>>,
  Expect<Equal<Absolute<'-0'>, '0'>>,
  Expect<Equal<Absolute<'10'>, '10'>>,
  Expect<Equal<Absolute<'-5'>, '5'>>,
  Expect<Equal<Absolute<-1_000_000n>, '1000000'>>,
  Expect<Equal<Absolute<9_999n>, '9999'>>,
]

`${T}` extends `-${infer U}` ? : 만약 문자열 T의 앞에 -가 붙어있으면

`${U}` : `${T}` : 문자열U를 리턴하고, -가 안붙어있으면 문자열T를 그대로 리턴한다.

 

`는 백틱입니다.

 

생각보다 너무 쉽다... 여기까지 올 정도면 이건 껌일 것 같다!