Typescript Count Substring of a String Literal Type

Ever wonder how can you count certain characters of a string literal type?

here is how:

type GetCountOfSubString<
String_ extends string,
SubString extends string,
Count extends unknown[] = []
> = String_ extends `${string}${SubString}${infer Tail}`
? GetCountOfSubString<Tail, SubString, [1, ...Count]>
: Count['length']
type NumberOfA = GetCountOfSubString<"a--a--aa--a","a"> // 5

playground

limitation: the count cannot exceed 999 because the max depth of TS recursion is only 1000

--

--

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)