Mapped types with template literals let you create new object types by changing keys using string patterns. This helps make your code flexible and reusable.
Mapped type with template literals in Typescript
type NewType<T> = {
[K in keyof T as `prefix_${string & K}_suffix`]: T[K]
};The as keyword lets you rename keys using template literal strings.
Use string & K to ensure the key is treated as a string for template literals.
type User = {
name: string;
age: number;
};
type PrefixedUser = {
[K in keyof User as `get_${string & K}`]: User[K];
};type Flags = {
isActive: boolean;
isAdmin: boolean;
};
type SuffixFlags = {
[K in keyof Flags as `${string & K}_flag`]: Flags[K];
};Uppercase utility type.type Options = {
debug: boolean;
verbose: boolean;
};
type UppercaseOptions = {
[K in keyof Options as Uppercase<string & K>]: Options[K];
};This program creates a new type where each key from Person is renamed with a 'readonly_' prefix and made readonly. Then it creates an object of that type and prints it.
type Person = {
firstName: string;
lastName: string;
age: number;
};
type ReadonlyPerson = {
readonly [K in keyof Person as `readonly_${string & K}`]: Person[K];
};
const person: ReadonlyPerson = {
readonly_firstName: "Alice",
readonly_lastName: "Smith",
readonly_age: 30
};
console.log(person);Mapped types with template literals only work with keys that can be converted to strings.
You can combine this with modifiers like readonly or ? (optional) for more control.
Template literal types are powerful for creating dynamic and descriptive keys in types.
Mapped types with template literals let you rename keys dynamically in object types.
This helps create flexible and reusable type patterns without repeating code.
Use as with template literals and string & K to transform keys safely.