Keyof and Typeof Operators in TypeScript

Keyof and Typeof Operators in TypeScript

Β·

3 min read

Keyof Operator

The keyof operator in TypeScript is used to create a union type of all the keys of a given object type. This allows developers to dynamically reference the keys of an object, enhancing type safety and reducing errors in code. For example, if you have an interface:

interface Person {
  name: string;
  age: number;
}

Using keyof, you can create a type that represents the keys of Person:

type PersonKeys = keyof Person; // "name" | "age"

Typeof Operator

The typeof operator is used to obtain the type of a variable or an object at runtime. It can be particularly useful for creating types based on existing variables or objects. For instance:

const user = {
  username: "john_doe",
  age: 30,
};

type UserType = typeof user; // { username: string; age: number; }

Keyof Example

Here’s how you can use keyof to access properties dynamically:

function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

const person: Person = { name: "Alice", age: 25 };
console.log(getProperty(person, "name")); // "Alice"

Typeof Example

Using typeof to create a new type from an object:

const settings = {
  theme: "dark",
  notificationsEnabled: true,
};

type SettingsType = typeof settings; // { theme: string; notificationsEnabled: boolean; }

Real-Life Use Cases

Keyof in Real Life

Consider a scenario where you want to validate form inputs based on an object structure:

interface FormFields {
  username: string;
  password: string;
}

function validateField<T>(fieldName: keyof T, value: any): boolean {
  // Simple validation logic
  return typeof value === 'string' && value.length > 0;
}

console.log(validateField<FormFields>("username", "user123")); // true

Typeof in Real Life

Using typeof to ensure consistent typing when passing configurations:

const config = {
  apiEndpoint: "https://api.example.com",
  timeout: 5000,
};

function fetchData(configOptions: typeof config) {
  console.log(`Fetching data from ${configOptions.apiEndpoint} with timeout ${configOptions.timeout}`);
}

fetchData(config); // Fetching data from https://api.example.com with timeout 5000

Using Both Together

The combination of keyof and typeof allows for powerful type manipulations. For instance, when you want to create a function that accepts only valid keys of an object defined by another variable:

const car = {
  make: "Toyota",
  model: "Camry",
};

type CarKeys = keyof typeof car;

function getCarDetail(key: CarKeys) {
  return car[key];
}

console.log(getCarDetail("make")); // "Toyota"

Combining both operators :

const product = {
  id: 1,
  name: "Laptop",
};

type ProductKeys = keyof typeof product;

function logProductDetail(key: ProductKeys) {
  console.log(`Product ${key}: ${product[key]}`);
}

logProductDetail("name"); // Product name: Laptop

Creating a mapped type using both operators:

type UserProfile = {
  id: number;
  email: string;
};

type UserProfileKeys = keyof UserProfile;

type UserProfileMap = {
  [K in UserProfileKeys]: string;
};

const userProfileExample: UserProfileMap = {
  id: "1",
  email: "example@example.com",
};

Summary

In this blog post, we explored the keyof and typeof operators in TypeScript. The keyof operator allows you to create union types from object keys, enhancing type safety and flexibility. Meanwhile, the typeof operator enables you to derive types from variables and objects dynamically. Together, they provide powerful tools for developers to write cleaner, safer code.

Did you find this article valuable?

Support webtalks by becoming a sponsor. Any amount is appreciated!

Β