Skip to content

Key Remapping

The Course
•
20 min study

A template literal type builds string types using backticks and substitutions, just as a JavaScript template builds text values. The example below constructs the property names onAdded and onRemoved from event keys. This describes allowed names; it does not allocate a handler object.

Start with names, then map keys

First form just the names: a template literal type substitutes each member of a string-literal union. The type alias below describes two strings; it does not create either callback. Capitalize is a built-in type helper turning the first character into uppercase. It is not a function you call on runtime text.

Build the names firstTypeScript
type Name = "added" | "removed";

type HookName = `on${Capitalize<Name>}`;

const first: HookName = "onAdded";
const second: HookName = "onRemoved";

console.log(first, second);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
onAdded onRemoved

Now read as inside the mapped type as “use this new property name.” This is different from the value assertion value as SomeType: key remapping does not assert that an unchecked value is safe.

A mapped type can rename each key using as. In Hooks below, K extends string ensures the key can be passed to the built-in Capitalize string transformation. The false branch is never, which drops non-string keys from this derived type. Capitalize changes the first character's type-level spelling, not a runtime name.

Read the mapping in steps: select a key, choose its new name, and preserve the old value relationship through T[K]. This combines conditional types, literal strings and indexed access; none of these syntax pieces should be mysterious now.

Keep remapping modest. A dozen layers of generated names can make errors harder to read. If runtime code needs those new names, construct the object explicitly or write and test a runtime transformation; a mapped type alone cannot produce it.

Predict, check, and run

Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.

Predict, then runTypeScript
type Hooks<T> = {
  [K in keyof T as K extends string ? `on${Capitalize<K>}` : never]: (
    value: T[K]
  ) => string;
};

type Events = {
  added: string;

  removed: number;
};

const hooks: Hooks<Events> = {
  onAdded: title => title.toUpperCase(),
  onRemoved: count => String(count)
};

console.log(hooks.onAdded("Types"));
console.log(hooks.onRemoved(2));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
TYPES
2

Read the compiler error

Predict the rejected relationship before checking. Read the real diagnostic and its source location; fix the contract or the value instead of hiding it with an assertion.

Find and fix the type errorTypeScript
type Labels<T> = {
  [K in keyof T as K extends string ? `${K}Label` : never]: string;
};

const labels: Labels<{ added: number }> = { added: "Added" };

console.log(labels);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The key line is TS2353: Object literal may only specify known properties, and 'added' does not exist in type 'Labels<{ added: number; }>'. The relationship that failed is a key: the mapped type renamed added, so the original name is now an excess property.

The renamed property is addedLabel. Key remapping does not accept the original key as a substitute.

Trace the contract before building

A remapped key changes the public name of a property while the mapped value can still refer to its original key. Trace one source property from K through the name transformation and then through the value type. Repeat with a second property of a different type to check that the relationship survives.

Consider which source keys your transformation accepts. String operations on key names need appropriate string-key evidence rather than assuming every possible key is text. Finally compare the declaration with the runtime object construction. A renamed mapped type does not rename actual object properties; the implementation must create the corresponding keys for a consumer to find them.

Build it yourself

Exercise

Key Remapping: practice

Labels renamed keys but gave every property the same type. Now make the value depend on the original key too. Write Getters<T>: for each string key K of T, a property named get + K with its first letter capitalized (title → getTitle), whose value is a zero-argument function returning T[K]. Build getters for a Book with title:string and pages:number, then print getTitle() uppercased and getPages() + 1: TYPES 121. Explain who constructs the runtime object.

Your workspaceTypeScript
// Start from the stated contract. Add a valid call and an edge case.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The as clause renames; the right-hand side can still use the original K. The standard library's intrinsic Capitalize<S> uppercases the first letter of a string literal type.

Hint 2: a first step

Start from the Labels declaration, put get in front of a capitalized K in the template, and replace the string value type with a function type returning the indexed type T[K].

Show one solution
One possible solutionTypeScript
type Getters<T> = {
  [K in keyof T as K extends string ? `get${Capitalize<K>}` : never]: () => T[K];
};

type Book = { title: string; pages: number };

const book: Book = { title: "Types", pages: 120 };

const getters: Getters<Book> = {
  getTitle: () => book.title,
  getPages: () => book.pages
};

console.log(getters.getTitle().toUpperCase(), getters.getPages() + 1);

Enable JavaScript to edit and type-check this example.

Text
TYPES 121

The as clause computes each new name (get${Capitalize<K>}), while the value type still uses the original key, so getTitle returns string and getPages returns number; that is why .toUpperCase() and + 1 both compile, and why getPages: () => "1" is rejected with TS2322. The K extends string test drops symbol or number keys, which can't go in a template. Nothing at runtime is generated: you construct the object literal yourself, and the mapped type only checks that it has exactly these names and function types.

Change it and test it

Add a third event key. Observe which property becomes required. Compare an ordinary string template at runtime with the type-only template; write one sentence distinguishing them.

Was this article helpful?

Your response is saved on this device.