DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

3 1

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
Enter fullscreen mode Exit fullscreen mode

playground

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

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay