TS Keyof

The keyof operator in TypeScript is used to create a type that represents the keys of an object. It is useful for working with object properties in a type-safe way.

Key Topics

Keyof Basics

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

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

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

let key: UserKeys = "name";
console.log(key); // name

Output

name

Explanation: The keyof operator creates a union type of the keys of the User interface. The variable key is constrained to these keys.

Keyof with Generics

The keyof operator can be combined with generics to create flexible and reusable type-safe functions.

function getValue(obj: T, key: K): T[K] {
    return obj[key];
}

const user = { id: 1, name: "Alice", email: "alice@example.com" };
console.log(getValue(user, "email")); // alice@example.com

Output

alice@example.com

Explanation: The function getValue uses keyof with generics to ensure that the key parameter is one of the keys of the obj, ensuring type safety.

Keyof in Constraints

You can use keyof in type constraints to limit what types are acceptable in a generic function or class.

class Storage {
    private store: T;

    constructor(store: T) {
        this.store = store;
    }

    get(key: K): T[K] {
        return this.store[key];
    }
}

const userStorage = new Storage({ id: 1, name: "Alice" });
console.log(userStorage.get("id")); // 1
console.log(userStorage.get("name")); // Alice

Output

1

Alice

Explanation: The Storage class uses keyof to restrict keys that can be accessed through the get method, ensuring type safety for object properties.

Key Takeaways

  • Keyof Basics: Use keyof to get a union of the keys of an object type.
  • Keyof with Generics: Combine with generics for reusable and type-safe functions.
  • Keyof in Constraints: Restrict keys to those present in a specific object type.
  • Best Practice: Use keyof for type-safe property access in objects.