rimo030 / type-challenges

Collection of TypeScript type challenges with online judge
https://tsch.js.org/
MIT License
3 stars 0 forks source link

no - 545 - printf #106

Open rimo030 opened 5 months ago

rimo030 commented 5 months ago
type FormatType = {
  s : string,
  d : number
  // ... 
}

type Format<T extends string> = T extends `${any}%${infer F}${infer R}` 
  ? F extends keyof FormatType
   ? (x: FormatType[F]) => Format<R> 
    :  Format<R> 
  : string
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<Format<'abc'>, string>>,
  Expect<Equal<Format<'a%sbc'>, (s1: string) => string>>,
  Expect<Equal<Format<'a%dbc'>, (d1: number) => string>>,
  Expect<Equal<Format<'a%%dbc'>, string>>,
  Expect<Equal<Format<'a%%%dbc'>, (d1: number) => string>>,
  Expect<Equal<Format<'a%dbc%s'>, (d1: number) => (s1: string) => string>>,
]
rimo030 commented 5 months ago

처음에는 아래와 같이 작성했었다.

type Format<T extends string> = T extends `${any}%${infer F}${infer R}` 
  ? F extends 's' 
   ? (s1 :string) => Format<R> 
   : F extends 'd'
    ? (d1 :number) => Format<R>  
    :  Format<R> 
  : string

다음과 같이 포맷타입 분리해 작성하면 재사용성을 높힐수 있다.

type FormatType = {
  s : string,
  d : number
  // ... 
}

type Format<T extends string> = T extends `${any}%${infer F}${infer R}` 
  ? F extends keyof FormatType
   ? (x: FormatType[F]) => Format<R> 
    :  Format<R> 
  : string