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: JohnOutput:

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: DoeOutput:

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: DoeOutput:
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: SpringfieldOutput:

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)}`);
});
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:

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: LaptopOutput:

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 objectOutput:

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: 5Output:

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.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.