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
🌐
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 - Another way to add a property to an object in TypeScript is to use type assertion:
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-add-property-to-object
How to Add a property to an Object in TypeScript | bobbyhadz
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.
Discussions

How do I dynamically assign properties to an object in TypeScript? - Stack Overflow
let user: User = new User(); (user ... lose its type here. ... This is the correct solution for one-off assignments. 2017-01-30T06:12:46.843Z+00:00 ... This answer worked for me because for facebook login I had to add properties to the window object. My first use of the as keyword in TypeScript... More on stackoverflow.com
🌐 stackoverflow.com
how to dynamically add a property to an object in typescript?
Try this var authorList = ['John Smith', 'Bill Jones']; //append author list to each result this.blogPostSearchResults.forEach(blogPost => blogPost['AuthorList'] = authorList); More on reddit.com
🌐 r/Angular2
2
3
August 29, 2017
How can I programmatically add property to object in TypeScript? - Ask a Question - TestMu AI (formerly LambdaTest) Community
In JavaScript, you can do this: var obj = {}; obj.prop = "value"; However, in TypeScript, this generates an error: “The property ‘prop’ does not exist on value of type '{}'”. How can I add new properties to an object in TypeScript? I’m looking for a method to handle typescript add ... More on community.testmuai.com
🌐 community.testmuai.com
0
August 1, 2024
properties - how do you add a property to an existing type in TypeScript? - Stack Overflow
You are using typescript, for example if you have a typo and write configurabl: true you'll get a compilation error as the object doesn't match the PropertyDescriptor type. And you're using typescript when you add your getter using interface Date so that from now on all date instance (as far ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/typescript › how to add a property to an object that doesn't exist in its type?
r/typescript on Reddit: How to add a property to an object that doesn't exist in its type?
September 28, 2022 -

EDIT: I just realized I could just deep clone the object and alter that one instead.


Heres a simplified example of what I'm trying to do:

const foo = (apiReponse: {A: number, B: number) => {
    return apiReponse.D = 123
}

Basically I am pass in an api response and using the type thats generated from codegen (apollo graphql). However I want to add a new field to it dynamically, however its throwing an error for the obvious reason.

How do I get around this or this just one big anti pattern?

Top answer
1 of 5
12
In case anyone is still wondering return {...apiResponse, D: 123};
2 of 5
1
Yes and no. Here's a little more explanation on what is going on. A JavaScript object is just a key-value dictionary/map where you can always add and remove values. That's great, but it allows developers to code in a style that is hard to debug. TypeScript to the rescue! Declaring a type makes sure that those objects only have the keys and values with the expected types, which is a lot easier to debug. Quick Answer: Please try to respect the TypeScript type-system. Maybe there's a different way to structure your code so you don't need to add random properties to objects. The real answer: TypeScrip _is_ JavaScript. You can always sneak a new property on an object, and unpack it later, it's totally fine as long as you keep the rest of the code unaware of this. TypeScript allows you to "force" the complier to skip type checks; you are basically telling it: "trust me bro". Doing a shallow-copy with the spread operator is nice, but note this is NOT adding the property to the previously existing object (which is probably for the best), but if you want to do it just like in JavaScript, then go ahead and use JavaScript: const foo = (apiReponse: {A: number, B: number}) => { (apiResponse as any).D = 123; // this property will be hidden and have no type return apiReponse; } To read the sneaked-in property from outside the function, you can also skip the safety of TypeScript: const fooResponse = foo(apiResponse); // TypeScript error: property D not in {A: number, B: number} console.log(fooResponse.D); // This works, but just like in JavaScript, D could be undefined or anything else console.log((fooResponse as any).D); If you do this, be ready to defend your case when your team (or linter) says that you shoudl never use type "any".
🌐
SPGuides
spguides.com › typescript-add-a-property-to-object
Add Property to TypeScript Object: 7 Practical Methods
April 21, 2025 - Use optional properties for flexibility: Mark properties with ? if they might not always be present. Consider partial types for incomplete objects: Use Partial<Type> when working with objects that will be populated gradually. TypeScript gives us many ways to add properties to objects.
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.
🌐
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 assign properties to an object using the following methods: Explicitly declaring object type: Explicitly typing objects at declaration time is the simplest approach, but it might not be feasible when properties ...
🌐
Melvin George
melvingeorge.me › blog › add-types-to-object-properties-in-typescript
How to add types to object properties in TypeScript? | MELVIN GEORGE
September 17, 2021 - To add types to object properties in TypeScript First, we can declare the variable name, followed by the : symbol (colon), followed by the {} symbol (Open and close curly brackets).
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript property
TypeScript Property | How to Add TypeScript Property with Methods?
February 20, 2023 - First, we have to set a property into the object in a typescript for appending a property that is optional on the interface and is allocated to the object with the help of the ‘?’ keyword; after that, we can append the property at a time with no type error.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
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 - The Record utility type allows you to constrict an object type whose properties are Keys and property values are Type. It has the following signature: Record<Keys, Type>. In our example, Keys represents string and Type, string as well.
🌐
Reddit
reddit.com › r/angular2 › how to dynamically add a property to an object in typescript?
r/Angular2 on Reddit: how to dynamically add a property to an object in typescript?
August 29, 2017 -

How can I dynamically add a property to an object in typescript? Here's a sample method:

processSearchResults(responseObject)
{
    var blogPostSearchResults = Object.assign(new GetBlogPostsResponse(), responseObject);
    this.blogPostSearchResults = blogPostSearchResults.CollectionResults;

var authorList = ['John Smith', 'Bill Jones'];

//append author list to each result
for (var blogPost in this.blogPostSearchResults)
{
    blogPost.AuthorList = authorList ;
}

}

In the example above, I'm taking an object with a particular definition, and then trying to create and assign a new property dynamically to provide an additional structure for html template view binding.

🌐
TestMu AI Community
community.testmuai.com › ask a question
How can I programmatically add property to object in TypeScript? - Ask a Question - TestMu AI (formerly LambdaTest) Community
August 1, 2024 - In JavaScript, you can do this: var obj = {}; obj.prop = "value"; However, in TypeScript, this generates an error: “The property ‘prop’ does not exist on value of type '{}'”. How can I add new properties to an object …
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › objects.html
TypeScript: Documentation - Object Types
Notice the given argument to createSquare is spelled colour instead of color. In plain JavaScript, this sort of thing fails silently. You could argue that this program is correctly typed, since the width properties are compatible, there’s no color property present, and the extra colour property is insignificant. However, TypeScript takes the stance that there’s probably a bug in this code. Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments.
🌐
Delft Stack
delftstack.com › home › howto › typescript › typescript add property to object
How to Dynamically Assign Properties to an Object in TypeScript | Delft Stack
March 13, 2025 - One of the most straightforward ways to dynamically assign properties to an object in TypeScript is through the use of index signatures. An index signature allows you to define the type of properties that can be added to an object without explicitly ...
🌐
xjavascript
xjavascript.com › blog › typescript-add-property-to-object
Adding Properties to Objects in TypeScript: A Comprehensive Guide — xjavascript.com
Adding a property to an object means creating a new key - value pair within that object. TypeScript enforces type checking, which means that when you add a property to an object, the type of the value you assign to the property must match the ...
🌐
xjavascript
xjavascript.com › blog › add-property-to-object-typescript
Adding Properties to Objects in TypeScript — xjavascript.com
When adding properties to an object, you need to ensure that the types of the new properties are compatible with the overall type definition of the object. Dot notation is the most straightforward way to add a property to an object in TypeScript.
🌐
Mimo
mimo.org › glossary › typescript › property
TypeScript Property: Syntax, Usage, and Examples
To add a property to an object in TypeScript, use type assertion or index signatures to extend the object dynamically.