kakasoo

문자열을 자르는 Split 타입 구현하기 본문

프로그래밍/TypeScript

문자열을 자르는 Split 타입 구현하기

카카수(kakasoo) 2023. 8. 11. 20:30
반응형
type Split<
  Target extends string,
  Separator extends string = ""
> = Target extends `${infer F}${Separator}${infer Rest}`
  ? [F, ...Split<Rest, Separator>]
  : Target extends ""
  ? []
  : [Target];

Join과 반대로 문자열을 분리하는 타입.

Target이 Separator를 기준으로 F와 Rest로 나뉠 수 있는 문자열일 경우 이 둘을 잘라 배열에 담는 타입이다.

Join 타입은 아래 링크들에서 확인할 수 있다.

 

https://kscodebase.tistory.com/682

 

타입 레벨에서 문자열 Join 구현하기

type ToString= T extends string ? T : never; type ToStringTuple= T extends string[] ? T : never; type Join = T extends [infer F, ...infer Rest] ? `${ToString}${Join}` : ''; 문자열로 이루어진 배열을 받아 Join하는 타입을 구현했다. type

kscodebase.tistory.com

https://kscodebase.tistory.com/709

 

타입 레벨에서 문자열 Join 구현하기 2

https://kscodebase.tistory.com/682 타입 레벨에서 문자열 Join 구현하기 type ToString= T extends string ? T : never; type ToStringTuple= T extends string[] ? T : never; type Join = T extends [infer F, ...infer Rest] ? `${ToString}${Join}` : '';

kscodebase.tistory.com

 

반응형