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
1174

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.
🌐
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 - A short little article about TypeScript’s inference system and how we can pre-define custom keys, dynamically · This may have duplicates, there may be articles already written about this. But, at the time when I needed this, I was not able to find something similar, not quite what I had in mind. const useVisible = <TName extends string>(name: TName) => { const [visible, setVisibility] = useState(false); const capitalized = (name.charAt(0).toLocaleUpperCase() + name.substring(1)) as Capitalize<TName>; type TCap = typeof capitalized; type VisibleReturn = { [k in `close${TCap}`]: () => void; } & { [k in `is${TCap}Visible`]: boolean; } & { [k in `open${TCap}`]: () => void; }; return { [`close${capitalized}`]: () => setVisibility(false), [`is${capitalized}Visible`]: visible, [`open${capitalized}`]: () => setVisibility(true), } as { [k in keyof VisibleReturn]: VisibleReturn[k]; }; };
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
2
0
June 10, 2022
How can I type an object with a dynamic property name?
OOh fun! function someFunction(dynamicName: Key) { return { [dynamicName]: 'foo', hardCodedName: 'bar' } as { [x in Key | 'hardCodedName']: string } } const someObject = someFunction('myExample') console.log(someObject.myExample) // Works console.log(someObject.hardCodedName) // Works console.log(someObject.whatever) // undefined! But TypeScript is no longer OK with it. Can't seem to type it without coercion. Does anyone have any ideas? I even tried satisfies, and dynamicName as Key, but doesn't work either. Here's the TS Play link. More on reddit.com
🌐 r/typescript
5
5
September 7, 2023
Creating object with dynamic keys
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
Help writing a type for object with dynamic keys.
Your type could be defined as either a dictionary (look up by "any" string type) or an object with set properties -- not both. While there may be wonky ways to get around it, it's not worth it and your best bet is to nest the record type to a property (also the recommended way of doing things) type normalizedUsers = { byId: Record; allIds: string[]; } More on reddit.com
🌐 r/typescript
4
4
February 4, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-create-objects-with-dynamic-keys-in-typescript
How to Create Objects with Dynamic Keys in TypeScript ? - GeeksforGeeks
July 23, 2025 - Mapped types in TypeScript allow us to create new types by transforming the properties of an existing type. We can leverage mapped types to dynamically generate object types with specific keys and value types.
🌐
freeCodeCamp
forum.freecodecamp.org › t › dynamic-object-keys-in-typescript › 516302
Dynamic object keys in TypeScript - The freeCodeCamp Forum
June 10, 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...
🌐
Total TypeScript
totaltypescript.com › tutorials › beginners-typescript › beginner-s-typescript-section › assigning-dynamic-keys-to-an-object › solution
Techniques for Typing Dynamic Object Keys | Total TypeScript
June 7, 2023 - It's just saying that this object here can contain any keys that we want, but they have to be strings. We can't pass numbers here, Booleans, or anything like that. This is one way to express this. 1:09 What you might have seen in the exercise here is that you had index types everywhere. It was saying, "You can't index this, can't use that to index this." This is saying basically that if we were to untie this record type, what it's saying is that this here is the index of the objects, the key of the object.
🌐
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 - In TypeScript, we can dynamically ... but it might not be feasible when properties need to be added dynamically · Using object index signature: This allows us to define the type of keys and value, and assign dynamic properties ...
Find elsewhere
🌐
Hackmamba
hackmamba.io › home › engineering › javascript dynamic object keys explained with examples
Javascript dynamic object keys explained with examples
May 26, 2026 - Use a Map when keys need to be non-strings such as objects or numbers, when insertion order must be guaranteed explicitly, or when you are adding and deleting entries frequently at scale. For plain data objects that need JSON serialization, dynamic object keys are the right tool.
🌐
DEV Community
dev.to › logrocket › how-to-dynamically-assign-properties-to-an-object-in-typescript-58fg
How to dynamically assign properties to an object in TypeScript - DEV Community
September 13, 2022 - Apart from primitives, the most ... to build an object dynamically, take advantage of the Record utility type or use the object index signature to define the allowed properties on the object....
🌐
Omarileon
omarileon.me › blog › typescript-dynamic-object-keys
mari. | How to Create Objects with Dynamic Keys in TypeScript
April 15, 2024 - So to sum it up, you can put together an object that uses dynamic keys with the Record type, which takes a type parameter for the keys of your object, and a parameter for the possible values. If you’re looking for a generic object, chances are you want this type: ... I wouldn’t recommend using this because of the any, but TypeScript will let you do whatever you want with it:
🌐
Linux Hint
linuxhint.com › dynamic-object-key-in-javascript
Linux Hint – Linux Hint
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-set-dynamic-property-keys-to-an-object-in-javascript
How to set dynamic property keys to an object in JavaScript?
December 8, 2022 - <!DOCTYPE html> <html> <head> <title>Dynamic Property Keys - defineProperty</title> </head> <body> <h3>Setting Dynamic Property Keys using Object.defineProperty()</h3> <p id="result2"></p> <script> let Employee = { name: 'Vinay', emp_id: 101 }; let key1 = "Company"; let key2 = 'role'; Employee[key1] = 'Tutorials Point'; Object.defineProperty(Employee, key2, { value: 'Software Engineer', writable: true, enumerable: true }); document.getElementById("result2").innerHTML = 'Employee.name: ' + Employee.name + '<br/>' + 'Employee.emp_id: ' + Employee.emp_id + '<br/>' + 'Employee[key1]: ' + Employee[key1] + '<br/>' + 'Employee[key2]: ' + Employee[key2]; </script> </body> </html>
🌐
Total TypeScript
totaltypescript.com › tutorials › beginners-typescript › assigning-dynamic-keys-to-an-object
Assigning Dynamic Keys to an Object | Total TypeScript
September 26, 2022 - 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.
🌐
Cloudhadoop
cloudhadoop.com › home
How to assign dynamic properties to an object in typescript
March 6, 2024 - ... Declare an object with the ... defeats the purpose of doing in typescript. ... Define an interface with index type signature to store key-value pairs with a specified type....
🌐
Jibin
jibin.tech › blog › indexable-object-in-typescript
Indexable object in typescript
October 25, 2020 - type User = { name: string, age: number, hobbies: string[] [key: string]: string | number | string[]} const person:User = { name: 'Jibin', age: 22, hobbies: ['games', 'chess', 'reading'] } Object.keys(person).map(key => { console.log(person[key]) // works now !!!}) « Simple monorepo setup with create-react-app and shared component library2020 In Review »
🌐
Infinitbility
infinitbility.com › how-to-add-new-property-to-object-in-typescript
How to add new property to object in typescript? - Infinitbility
February 28, 2022 - Then you are right because everyone is wishing for the true love and partner of their life but few of them is able to find the loving partner of their life. And if they find the partner it is not necessary that he/she will stay for the life long time with him.
🌐
AstroDeck
xspdf.com › resolution › 56175074.html
xspdf — PDF Generation & Processing API for Developers | xspdf
curl -X POST https://api.xspdf.com/v1/generate \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "html": "<h1>Invoice</h1><p>Total: $99</p>", "format": "A4", "margin": "1cm" }' ... Everything you need to build document workflows. Simple REST API, powerful features. Create PDFs from HTML, templates, or dynamic data.