Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Type Operators

TypeScript key remapping with as

Reference for the as clause in TypeScript mapped types: rename keys with template literals, filter keys with never, map over unions and build getters and event maps.

A mapped type normally keeps the keys it loops over. The as clause (TypeScript 4.1) changes that: [K in keyof T as NewKey]: ... computes a new key for each source key. You can rename keys with template literal types, or drop them by remapping to never.

The as expression can use K, so it can transform names (get${Capitalize<K>}) or test them in a conditional type and remove the ones you do not want.

TypeScript
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

Try it

TypeScript Renaming keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Filtering keys and unions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
type Remapped<T> = {
  [K in Keys as NewKey<K>]: ValueType;
};
Part Description
K in Keys Loop variable over a union, normally keyof T, or a union of object types (S in Shape).
NewKey<K> Must produce string, number or symbol literals (or a union of them). never removes the entry.
ValueType The property type; can use both K and T[K].

Edge cases:

  • keyof T includes string | number | symbol. In template literals use string & K to keep only string keys, otherwise you get an error ("Type 'symbol' is not assignable to type 'string | number | bigint | boolean | null | undefined'").
  • If NewKey produces a union, one source key becomes several properties.
  • Two source keys that map to the same new key merge: their value types are unioned.

Usage notes

  • Remapping and modifiers: a mapped type with as over keyof T is still homomorphic, so readonly and optional flags are kept.
  • Event maps: on${Capitalize<K>} is a common way to derive handler names from an event table.
  • Filter by type, not just name: test T[K] extends X inside as.
  • Mapping over objects: [S in Union as S["kind"]] turns a discriminated union into a keyed table.
  • Prefer Omit/Pick when you only drop or keep keys by name; as is for computed names.
  • Template literal combinatorics can blow up when a union of keys is mapped to a union of names; check compile times.
  • Compile-time only.