Keyof, Index Signatures, and Custom Mappings - Textnotes

Keyof, Index Signatures, and Custom Mappings


Learn how to use mapped types in TypeScript to create flexible and reusable type transformations. This module explains the keyof operator, index signatures, and custom mapped types with practical examples.

1. Keyof Operator

The keyof operator generates a union of string literal types representing the keys of an object type.

Basic Example


interface User {
id: number;
name: string;
email: string;
}

type UserKeys = keyof User; // "id" | "name" | "email"

Usage Example


function getProperty(obj: User, key: keyof User) {
return obj[key];
}

const user: User = { id: 1, name: "Muni", email: "muni@example.com" };
const name = getProperty(user, "name"); // Valid
// const age = getProperty(user, "age"); // Error

The keyof operator ensures type-safe access to object properties.

2. Index Signatures

Index signatures define types for properties that are not known in advance. They are commonly used for dynamic objects or dictionaries.

Basic Example


interface StringMap {
[key: string]: string;
}

const translations: StringMap = {
hello: "Hola",
goodbye: "Adiós"
};

Example with Number Index


interface NumberMap {
[index: number]: string;
}

const names: NumberMap = ["Muni", "Ravi"];

Index signatures allow flexible objects while maintaining type safety.

3. Custom Mapped Types

Mapped types allow you to transform existing types into new types using keyof and property modifiers.

Basic Example


type User = {
id: number;
name: string;
email: string;
};

type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};

const user: ReadonlyUser = { id: 1, name: "Muni", email: "muni@example.com" };
// user.name = "Ravi"; // Error

Partial Using Mapped Type


type PartialUser = {
[K in keyof User]?: User[K];
};

Mapped types are the foundation for TypeScript’s built-in utility types like Partial, Readonly, Pick, and Record.

Conclusion

Mapped types in TypeScript, combined with keyof and index signatures, allow developers to create flexible, reusable, and type-safe transformations. Mastering mapped types is essential for advanced type manipulation and scalable application development.