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
470 stars 56 forks source link

type-challenges-solutions/en/medium-endswith #196

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

EndsWith

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-endswith.html

DaniGuardiola commented 2 years ago

Why not use ${string} instead of ${any}? It can't really be anything else, can it?

ghaiklor commented 2 years ago

@DaniGuardiola if it works with a string than it's ok too. I chose it to be an indicator to show I don't care about the end.

JanessaTech commented 1 week ago

The solution above is simpler than mine. Here is mine just as alternative:

  type EndsWith<T extends string, U extends string, acc extends string = ''> = U extends ''
  ? true
  : T extends `${infer rest}${infer end}`
    ? end extends ''
        ? `${rest}${acc}` extends U ? true : false
        : `${end}${acc}` extends U ? true : EndsWith<rest, U, `${end}${acc}`>
    : never