ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
474 stars 57 forks source link

type-challenges-solutions/en/medium-join #238

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

Join

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-join.html

Beraliv commented 2 years ago

Great job! Thank you for the article!

TIL: I really like the way you mention references at the end of the article, really helpful for people who are lost with the solution because of some missed TS feature or term

Beraliv commented 2 years ago

In case someone faces the problem with Type instantiation is excessively deep and possibly infinite, you will need to use Tail-Recursion Elimination on Conditional Types

The updated solution can look as following:

type JoinV2<T extends string[], U extends string | number, V extends string = ''> = T extends [
  infer S extends string,
  ...infer R extends string[]
]
  ? JoinV2<R, U, `${V}${V extends '' ? '' : U}${S}`>
  : V;

It also has its limitations around 998 recursive calls

JanessaTech commented 2 months ago

Here is my similar solution:


  type Join<T extends unknown[], U extends string | number = ',', acc extends string = ''> = T extends [infer F extends string, ...infer R]
  ? Join<R, U, `${acc}${F}${R extends [] ? '' : U}`>
  : acc