You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

19 lines
608 B

import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<SnakeCase<'hello'>, 'hello'>>,
Expect<Equal<SnakeCase<'userName'>, 'user_name'>>,
Expect<Equal<SnakeCase<'getElementById'>, 'get_element_by_id'>>,
Expect<Equal<SnakeCase<'getElementById' | 'getElementByClassNames'>, 'get_element_by_id' | 'get_element_by_class_names'>>,
]
type SnakeCase<
T extends string,
Acc extends string = '',
> =
T extends `${infer Head}${infer Tail}`
? Head extends Lowercase<Head>
? SnakeCase<Tail, `${Acc}${Head}`>
: SnakeCase<Tail, `${Acc}_${Lowercase<Head>}`>
: Acc
;