Dynamically Access Object Properties by String in TypeScript

Recently, I was working on a dynamic form in a TypeScript project, and the form fields were not fixed. In form, the field names were coming from user input. With this, it is difficult to update the form values because I didn’t know the exact property names in advance.

As a solution, I used a dynamic property access method to access object properties using strings instead of fixed keys.

In this tutorial, I’ll explain how to dynamically access object properties by string in TypeScript with the help of real-time examples.

Understanding TypeScript Object Property Access

TypeScript, a superset of JavaScript, provides robust typing features that help in catching errors early during development. However, accessing object properties dynamically can sometimes be tricky due to TypeScript’s strict type system. Let’s start with the basics.

Static Property Access

In TypeScript, accessing object properties statically is straightforward. Consider the following example:

interface User {
  firstName: string;
  lastName: string;
  age: number;
}

const user: User = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

console.log(user.firstName); // Output: John

Output:

Object Properties in TypeScript

Here, we access the firstName property directly using dot notation.

Check out: Remove a Character from a String in TypeScript

Dynamic Property Access

Dynamic property access is necessary when the property name is determined at runtime. For example, if you have a property name stored in a variable, you can use bracket notation to access the property:

const propertyName = "lastName";
console.log(user[propertyName]); // Output: Doe

Output:

Access Object Properties in TypeScript

Using keyof and Indexed Access Types

To ensure type safety while accessing properties dynamically, TypeScript provides the keyof operator and indexed access types. The keyof operator returns a union of all the keys in an object type. Here’s how you can use it:

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

const lastName = getProperty(user, "lastName");
console.log(lastName); // Output: Doe

Output:

In this example, the getProperty function ensures that the key is a valid property of the object, providing type safety.

Practical Examples to Dynamically Access Object Property in TypeScript

Let’s dive into some practical examples that illustrate how to dynamically access object properties in TypeScript.

Example 1: User Profile

Imagine you are building a user profile page for an application. The user data is fetched from an API, and you need to display various properties based on user interaction.

interface UserProfile {
  id: number;
  username: string;
  email: string;
  address: {
    street: string;
    city: string;
    state: string;
    zipCode: string;
  };
}

const userProfile: UserProfile = {
  id: 1,
  username: "johndoe",
  email: "john.doe@example.com",
  address: {
    street: "123 Elm St",
    city: "Springfield",
    state: "IL",
    zipCode: "62704"
  }
};

function displayProperty(obj: any, key: string) {
  console.log(obj[key]);
}

displayProperty(userProfile, "username"); // Output: johndoe
displayProperty(userProfile.address, "city"); // Output: Springfield

Output:

TypeScript Access Object Properties

Check out: Replace Characters in a String Using TypeScript

Example 2: Configurable Dashboard

Consider a configurable dashboard where users can select which data to display. The selected data points are stored in an array, and you need to access these properties dynamically.

interface DashboardConfig {
  widgets: {
    [key: string]: {
      title: string;
      data: any;
    };
  };
}

const dashboardConfig: DashboardConfig = {
  widgets: {
    weather: {
      title: "Weather",
      data: { temperature: 72, condition: "Sunny" }
    },
    news: {
      title: "News",
      data: { headline: "Local Man Wins Lottery", details: "A Springfield resident..." }
    }
  }
};

const selectedWidgets = ["weather", "news"];

selectedWidgets.forEach(widgetKey => {
  const widget = dashboardConfig.widgets[widgetKey];
  console.log(`Title: ${widget.title}`);
  console.log(`Data: ${JSON.stringify(widget.data)}`);
});
Dynamic property access in TypeScript objects

Type Safety with Record and Partial

TypeScript’s utility types Record and Partial can be very useful when dealing with dynamic object properties.

Using Record type

The Record type is used to define an object type with a specific set of keys and values. This is particularly useful when you know the keys ahead of time but not the values.

type WidgetData = Record<string, any>;

const widgetData: WidgetData = {
  weather: { temperature: 72, condition: "Sunny" },
  news: { headline: "Local Man Wins Lottery", details: "A Springfield resident..." }
};

function getWidgetData(widget: keyof WidgetData) {
  return widgetData[widget];
}

console.log(getWidgetData("weather")); // Output: { temperature: 72, condition: 'Sunny' }

Output:

Access object Property using TypeOf operator in TypeScript

Check out: Check if a String Contains a Substring in TypeScript

Using Partial type

The Partial type makes all properties of a type optional. This is useful when you are dealing with objects that may have incomplete data.

interface Product {
  id: number;
  name: string;
  price: number;
  description?: string;
}

const partialProduct: Partial<Product> = {
  id: 1,
  name: "Laptop"
};

function printProductDetails(product: Partial<Product>) {
  console.log(`ID: ${product.id}`);
  console.log(`Name: ${product.name}`);
  if (product.description) {
    console.log(`Description: ${product.description}`);
  }
}

printProductDetails(partialProduct); // Output: ID: 1, Name: Laptop

Output:

Use Opeartors to access object properties in TypeScript

Advanced Techniques to Dynamically Access Object Properties in TypeScript

Using the ‘in’ Operator

The in operator can be used to check if a property exists in an object before accessing it. This is useful to avoid runtime errors.

interface Car {
  make: string;
  model: string;
  year: number;
}

const car: Car = {
  make: "Tesla",
  model: "Model S",
  year: 2025
};

function printCarProperty(obj: any, key: string) {
  if (key in obj) {
    console.log(obj[key]);
  } else {
    console.log(`Property ${key} does not exist on the object`);
  }
}

printCarProperty(car, "make"); // Output: Tesla
printCarProperty(car, "color"); // Output: Property color does not exist on the object

Output:

TypeScript Methods to Access Object Properties

Check out: Capitalize the First Letter of String in TypeScript

Type Guards

Type guards are a way to narrow down the type of an object within a conditional block. This is particularly useful when dealing with unions or unknown types.

interface Admin {
  role: "admin";
  permissions: string[];
}

interface Guest {
  role: "guest";
  visitCount: number;
}

type User = Admin | Guest;

function isAdmin(user: User): user is Admin {
  return user.role === "admin";
}

function printUserRole(user: User) {
  if (isAdmin(user)) {
    console.log(`Admin with permissions: ${user.permissions.join(", ")}`);
  } else {
    console.log(`Guest with visit count: ${user.visitCount}`);
  }
}

const adminUser: Admin = { role: "admin", permissions: ["read", "write"] };
const guestUser: Guest = { role: "guest", visitCount: 5 };

printUserRole(adminUser); // Output: Admin with permissions: read, write
printUserRole(guestUser); // Output: Guest with visit count: 5

Output:

Use Type Guards to Access Object Properties in TypeScript

Conclusion

In this TypeScript tutorial, we have learned the methods through which we can dynamically access the object properties by string in TypeScript.

By using TypeScript’s type system, utility types, and type guards, we can ensure type safety and avoid common pitfalls. Whether you are building a dynamic user interface or processing flexible data structures, the techniques covered in this tutorial will help you handle dynamic property access effectively.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.