Typescript Test Your Generic Type Part 1

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
type Expect<T, U>= T extends U ? U extends T ? true : false : false type r1 = Expect<GetCountOfSubString<"a--a--aa--a","a">,5> // true, success check
type r2 = Expect<GetCountOfSubString<"a--a--aa--a","a">,1> // false, fail check
type Assert<T extends true> = T // be anything after '=', doesn't matter
type Expect<T, U>= T extends U ? U extends T ? true : false : false type Assert<T extends true> = T // be anything after '=', doesn't mattertype r1 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,5>> // true, pass test
type r2 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,1>> // false, fail test
type r1 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,5>> // true, pass test
// @ts-expect-error
type r2 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,1>> // false, fail test
type GetCountOfSubString<
String_ extends string,
SubString extends string,
Count extends unknown[] = []
> = "BUG!!"
type Expect<T, U>= T extends U ? U extends T ? true : false : false type Assert<T extends true> = T // be anything after '=', doesn't mattertype r1 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,5>> // true, pass test
// @ts-expect-error
type r2 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,1>> // false, fail test
type GetCountOfSubString<
String extends string,
SubString extends string,
Count extends unknown[] = []
> = 1
type Expect<T, U>= T extends U ? U extends T ? true : false : false type Assert<T extends true> = T // be anything after '=', doesn't mattertype r1 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,5>> // true, pass test// @ts-expect-error
type r2 = Assert<Expect<GetCountOfSubString<"a--a--aa--a","a">,1>> // false, fail test
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const assert = <T extends true>() => {
//
}
assert<Expect<GetCountOfSubString<'a--a--aa--a', 'a'>, 5>>() // true, pass test
// @ts-expect-error
assert<Expect<GetCountOfSubString<'a--a--aa--a', 'a'>, 1>>() // false, fail test

--

--

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