0Pricing
TypeScript Academy · Lesson

Key remapping & template literal types

Remap keys with “as”, build keys via template literals (Capitalize/Uncapitalize), and filter properties by name patterns.

Intro

Goal: Use key remapping (the as clause) with template literal types to rename, generate, or drop properties by name patterns.

  • Rename keys: K as NewK
  • Filter keys with never
  • Compose names: `get${Capitalize<K>}`

Rename keys

Rename keys with as. Example: Convert snake_case names to camelCasee.

type Original = { first_name: string; last_name: string }

type Camelize<T> = {
  [K in keyof T as K extends `${infer A}_${infer B}`
    ? `${A}${Capitalize<B>}`
    : K]: T[K]
}

type UserCamel = Camelize<Original>  // { firstName: string; lastName: string }

All lessons in this course

  1. Mapped types with +/-readonly and +/-?
  2. Key remapping & template literal types
  3. String-pattern typing (route params, event names)
← Back to TypeScript Academy