이 글은 제가 타입챌린지를 하면서 해석한 내용을 적는 글입니다. 틀린 내용이 있으면 댓글 달아주시면 감사하겠습니다.
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를 그대로 리턴한다.
`는 백틱입니다.
생각보다 너무 쉽다... 여기까지 올 정도면 이건 껌일 것 같다!
'Language > Typescript' 카테고리의 다른 글
타입챌린지 : 599-Merge (medium) (2) | 2023.04.15 |
---|---|
타입챌린지 : 531-String to Union (medium) (0) | 2023.04.11 |
타입챌린지 : 527-Append to object (medium) (0) | 2023.04.07 |
타입챌린지 : 459-Flatten (medium) (0) | 2023.04.06 |
타입챌린지 : 298-Length of String (medium) (0) | 2023.04.05 |