Skip to content

类型挑战

INFO

什么? TypeScript 你还不会? 你 out 啦,快来做类型体操吧。

TS Question 1

Got a TypeScript challenge for ya. How would you write a ToCamelCaseKeys type helper? (twitter)

Playground

TypeScript
interface RandomKeys {
  snake_case: string
  PascalCase: boolean
  camelCase: number
  SCREAMING_SNAKE_CASE: bigint
}

/**
 * TS Question - how do you transform ⬆️ into ⬇️?
 */

interface CoercedKeys {
  snakeCase: string
  pascalCase: boolean
  camelCase: number
  screamingSnakeCase: bigint
}

type TransformLowercase<T extends string> = T extends `${string}_${string}` ? Lowercase<T> : T
type SplitUnderscore<T extends string> = T extends `${infer A }_${infer B }` ? [A, ...SplitUnderscore<B>] : [T]
type Concat<T extends string[]> = T extends [infer A extends string, ...infer Rest extends string[]]  ? `${Capitalize<A>}${Concat<Rest>}` : ''

type Result = { [k in keyof RandomKeys as Uncapitalize<Concat<SplitUnderscore<TransformLowercase<k>>>>]: RandomKeys[k] }

type IsItWorking = Result extends CoercedKeys ? true : false