Index signatures

It is possible to denote obj as any, but that defeats the whole purpose of using typescript. obj = {} implies obj is an Object. Marking it as any makes no sense. To accomplish the desired consistency an interface could be defined as follows, using an index signature

interface LooseObject {
    [key: string]: any
}

var obj: LooseObject = {};

OR to make it compact:

var obj: {[k: string]: any} = {};

LooseObject can accept fields with any string as key and any type as value.

obj.prop = "value";
obj.prop2 = 88;

The real elegance of this solution is that you can include typesafe fields in the interface.

interface MyType {
    typesafeProp1?: number,
    requiredProp1: string,
    [key: string]: any
}

var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number

obj.prop = "value";
obj.prop2 = 88;

Record<Keys,Type> utility type

Update (August 2020): @transang brought up the Record<Keys,Type> utility type in comments

Record<Keys,Type> is a Utility type in typescript. It is a much cleaner alternative for key-value pairs where property-names are not known. It's worth noting that Record<Keys,Type> is a named alias to {[k: Keys]: Type} where Keys and Type are generics. IMO, this makes it worth mentioning here

For comparison,

var obj: {[k: string]: any} = {};

becomes

var obj: Record<string,any> = {}

MyType can now be defined by extending Record type

interface MyType extends Record<string,any> {
    typesafeProp1?: number,
    requiredProp1: string,
}

While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.

Answer from Akash on Stack Overflow
Top answer
1 of 16
1173

Index signatures

It is possible to denote obj as any, but that defeats the whole purpose of using typescript. obj = {} implies obj is an Object. Marking it as any makes no sense. To accomplish the desired consistency an interface could be defined as follows, using an index signature

interface LooseObject {
    [key: string]: any
}

var obj: LooseObject = {};

OR to make it compact:

var obj: {[k: string]: any} = {};

LooseObject can accept fields with any string as key and any type as value.

obj.prop = "value";
obj.prop2 = 88;

The real elegance of this solution is that you can include typesafe fields in the interface.

interface MyType {
    typesafeProp1?: number,
    requiredProp1: string,
    [key: string]: any
}

var obj: MyType ;
obj = { requiredProp1: "foo"}; // valid
obj = {} // error. 'requiredProp1' is missing
obj.typesafeProp1 = "bar" // error. typesafeProp1 should be a number

obj.prop = "value";
obj.prop2 = 88;

Record<Keys,Type> utility type

Update (August 2020): @transang brought up the Record<Keys,Type> utility type in comments

Record<Keys,Type> is a Utility type in typescript. It is a much cleaner alternative for key-value pairs where property-names are not known. It's worth noting that Record<Keys,Type> is a named alias to {[k: Keys]: Type} where Keys and Type are generics. IMO, this makes it worth mentioning here

For comparison,

var obj: {[k: string]: any} = {};

becomes

var obj: Record<string,any> = {}

MyType can now be defined by extending Record type

interface MyType extends Record<string,any> {
    typesafeProp1?: number,
    requiredProp1: string,
}

While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.

2 of 16
120

This solution is useful when your object has Specific Type. Like when obtaining the object to other source.

let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.
🌐
Reddit
reddit.com › r/typescript › what would the type be for an object that i want to dynamically add key/value pairs to?
r/typescript on Reddit: What would the type be for an object that I want to dynamically add key/value pairs to?
February 11, 2026 -

I have an empty object x that I want to add instances of classes to by string. How can I get type enforcement for such a thing?

example:

class A {
}
class B {
}
class C {
}


const x: {[key: string]: A | B} = {};


x["a"] = new A();
x["b"] = new B();
x["c"] = new C(); // should give an error

Playground:

https://www.typescriptlang.org/play/?ssl=12&ssc=42&pln=1&pc=1#code/MYGwhgzhAECC0G8BQBfJpIwEKNe8U0AwrmugPYB2EALtAB4BciA2gNYCmAns7QE4BLSgHMAus3gAfaFhTQAvIhQBuJEnosARGE2iF0ShwDucABQBKVRs0AjXfsMmsFq1uD3Fj4i+gB6X9AQABbkAK4gACbQwgIAbhzQYJTQHHx85HxAA

Discussions

Dynamic object keys in TypeScript
I have a problem when setting the type of a dynamic object in TypeScript because the object that i create has dynamic keys and three that are not. Here’s how i defined the type for the object: interface GraphReturns { … More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
June 9, 2022
create object with dynamic keys in typescript | The ASP.NET Forums
We are excited to announce that the ASP.NET Forums are moving to the new Microsoft Q&A experience. Learn more > ... ASP.NET Forums/General ASP.NET/HTML, CSS and JavaScript/create object with dynamic keys in typescript More on forums.asp.net
🌐 forums.asp.net
Creating object with dynamic keys - javascript
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Here's the situation: I have a function that I need to create an object. That object uses variables for both its keys and ... More on stackoverflow.com
🌐 stackoverflow.com
Dynamically assign object property
You're loosing the type for the prop and value on Object.entries, more about it here : https://alexharri.com/blog/typescript-structural-typing More on reddit.com
🌐 r/typescript
8
5
July 18, 2023
🌐
LogRocket
blog.logrocket.com › home › how to dynamically assign properties to an object in typescript
How to dynamically assign properties to an object in TypeScript - LogRocket Blog
October 15, 2024 - Using the Record utility type: With the Record type, we can create an object type with specified keys and values, as in Record<string, string>, where both the keys and values are of type string · Using the Map data type: Using a Map object ...
🌐
xjavascript
xjavascript.com › blog › dynamically-add-key-value-to-object-typescript
Dynamically Adding Key-Value Pairs to Objects in TypeScript — xjavascript.com
Dynamic property addition refers to the process of adding new key-value pairs to an object after it has been created.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-dynamically-add-key-to-object
How to Dynamically Add a Key to an Object in TypeScript
By using Object.assign(), we can merge the original object with a new object containing the dynamically added key-value pair. This method is useful for adding multiple dynamic keys to an object. Dynamically adding keys to objects in TypeScript provides a powerful way to adapt your data structures ...
🌐
Webdevtutor
webdevtutor.net › blog › typescript-add-key-value-pair-to-object
How to Add Key-Value Pair to Object in TypeScript
This method allows for dynamic key assignment. Here's an example: const myObj: { [key: string]: string } = { key1: "value1", key2: "value2" }; const newKey = "key3"; const newValue = "new value"; myObj[newKey] = newValue; In this example, we define an object myObj with keys key1 and key2.
🌐
Medium
medium.com › @jofaval › objecy-with-dynamic-keys-in-typescript-468c358a5f8b
Objects with Dynamic Keys in TypeScript | by Pepe Fabra Valverde | Medium
October 20, 2023 - If we want to set up the type of a key to a very specific value, we can do so by defining a literal type (which can be twitched through inference). So… instead of defining the key, we have to do the little trick of defining the key and then ...
🌐
Total TypeScript
totaltypescript.com › tutorials › beginners-typescript › beginner-s-typescript-section › assigning-dynamic-keys-to-an-object
Assigning Dynamic Keys to an Object | Total TypeScript
June 7, 2023 - Seeing “index” in a type error message usually refers to the key of an object. In this lesson are a few techniques for properly typing dynamic object keys.
Find elsewhere
🌐
Cloudhadoop
cloudhadoop.com › home
How to assign dynamic properties to an object in typescript
March 6, 2024 - Above, the interface is declared with string keys and value types any. ... obj.name = "Ram"; obj.salary = 5000; console.log(obj); // Outputs: { "name": "Ram", "salary": 5000 } You can also use a shorter syntax for inline index signatures. var obj: { [k: string]: any } = {}; obj.name = "ram"; obj.salary = 5000; console.log(obj); //{ "name": "ram", "salary": 5000} ... TypeScript’s Record<K, V> object can store key-value pairs with specific types.
🌐
freeCodeCamp
forum.freecodecamp.org › t › dynamic-object-keys-in-typescript › 516302
Dynamic object keys in TypeScript - The freeCodeCamp Forum
June 9, 2022 - I have a problem when setting the type of a dynamic object in TypeScript because the object that i create has dynamic keys and three that are not. Here’s how i defined the type for the object: interface GraphReturns { [key: string]: { '%': number, value: number, '�umulated': number }, total: number, 'total_%': number, date: string } The errors i get: Property ‘total’ of type ‘number’ is not assignable to ‘string’ index type ‘{ ‘%’: number; value: number; ‘�umu...
🌐
SamanthaMing
samanthaming.com › tidbits › 37-dynamic-property-name-with-es6
How to Set Dynamic Property Keys with ES6 🎉 | SamanthaMing.com
With ES6, you can now directly use a variable as your property key in your object literal. YAY! 👏 · let cake = '🍰'; // ❌ Old way requires 2 steps let pan = { id: 1, }; pan[cake] = '🥞'; // ✅ YAY, much easier with ES6 let pan = { ...
🌐
Sean C Davis
seancdavis.com › posts › mapping-dynamic-object-keys-in-typescript
Mapping Dynamic Object Keys in TypeScript | Sean C Davis
Consider the example from the dynamic property map post: const buttonClassMap = { dark: "bg-black text-white", light: "bg-gray text-black", }; const theme = "light"; buttonClassMap[Object.keys(buttonClassMap).includes(theme) ? theme : "dark"]; The beauty of TypeScript is that if theme is defined elsewhere in the code, we can ensure it’s the right type and not need to do this checking. The problem is that it’s not as straightforward as it seems it should be. Let’s add a Button type with a theme property, and then assign our theme variable to that type.
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-add-property-to-object
How to Add a property to an Object in TypeScript | bobbyhadz
The interface EmployeeData extends from the Record constructed type with string keys and any type values. The interface sets a specific type for the 3 properties that we know about in advance. If we try to set the role, salary or color properties to an incompatible type, we'd get an error. Use computed property names to set an object's property name from a variable in TypeScript.
🌐
Reddit
reddit.com › r/typescript › dynamically assign object property
r/typescript on Reddit: Dynamically assign object property
July 18, 2023 -

Hi everyone, please help me with this compile error:

interface Person {
    id: string,
    name?: string,
    age?: number
}

const originalPerson: Person = {id: "123", name: "Original"}
const updatePayload: Person = {id: "123", name: "Updated"};

Object.entries(updatePayload).forEach(([key, value]) => {
    originalPerson[key as keyof Person] = value;
});

The last line is having this error:

Looks like `value` is of type `any`, and `originalPerson[key as keyof Person]` is of type `never`. I also observed that if I change the type of `age` from `number` to `string` then the error will go away.

Not sure how can I fix this issue. For context: the original object is a very big object with multiple nested levels stored in a reactive store, while the updatePayload object is much much smaller so I may not want to reassign the original object to a new one every time I want to make an update.

🌐
Codez Up
codezup.com › home › 3 ways to add dynamic key to object in javascript
3 ways to Add Dynamic Key to Object in Javascript | Codez Up
September 7, 2021 - So, in my case, what I have done, I have used the above ES6 method and convert an array to an object of key-value pairs and then return the data to the frontend. So, I am going to share two cases, one is when we want to convert an array of strings to an array of objects, and in the 2nd case, we convert the array to a single object with dynamic key creation at runtime using reduce() function.
🌐
xjavascript
xjavascript.com › blog › add-key-value-to-object-typescript
Adding Key-Value Pairs to Objects in TypeScript — xjavascript.com
Adding key-value pairs to objects in TypeScript is a common and essential operation. We have explored different ways to achieve this, including dot notation, bracket notation, Object.assign(), and the spread operator.
🌐
Stack Abuse
stackabuse.com › bytes › how-to-add-a-property-to-an-object-in-typescript
How to Add a Property to an Object in TypeScript
September 19, 2023 - An index signature is a way to tell TypeScript that an object could have any number of properties. Here's how it works: let person: { [key: string]: any } = { firstName: "John", lastName: "Doe", age: 25 }; person.middleName = "William"; // This works! In this example, we've defined person as an object that can have any number of properties, each with a string key and any type of value.