Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Typescript Template Literals convert array to a list

I have an array:

 const arr = ['a', 'b', 'c']

That I want to convert to a comma-separated list - 'a,b,c'. Is there any way to convert it's type also using the new Template Literals feature?

function toList<T>(arr: T[]) {
  return arr.join(',')
}

const list: 'a,b,c' = toList(arr);
question from:https://stackoverflow.com/questions/65899183/typescript-template-literals-convert-array-to-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is your solution:

const arr = ['a', 'b', 'c'] as const;

type Arr = typeof arr;

type Elem = string
type Mapper<
  Arr extends ReadonlyArray<Elem>,
  Result extends string = ''
  > = Arr extends []
  ? Result
  : Arr extends [infer H]
  ? H extends Elem
  ? `${Result},${H}`
  : never
  : Arr extends readonly [infer H, ...infer Tail]
  ? Tail extends ReadonlyArray<Elem>
  ? H extends Elem
  ? Result extends '' ? Mapper<Tail, `${Result}${H}`> : Mapper<Tail, `${Result},${H}`>
  : never
  : never
  : never;

type Result = Mapper<Arr> //  "a,b,c"


function toList<T extends ReadonlyArray<string>>(arr: T) {
  return arr.join(',') as Mapper<T>
}

const list = toList(arr);

Playground link

Here you can find more interesting examples

P.S. Please, keep in mind, it is not 100% type safe because I used casting operator as


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...