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.
🌐
Sentry
sentry.io › sentry answers › javascript › how can i add a key-value pair to a javascript object?
How Can I Add a Key-Value Pair to a JavaScript Object? | Sentry
Property accessors use dot notation or bracket notation to give access to an object’s properties, which can also be called keys. You can use them to add a key-value pair to an object.
Discussions

TypeScript- How to add a Key Value pair to each object in an Array?
I'd like to add the dates to the array of objects as a key value pair {"Date": "10-12-18"}. ... I want something like... Copy[ {"name":"One", "age": "4", "Date": "10-12-18"}, .... How can I do this in TypeScript? More on stackoverflow.com
🌐 stackoverflow.com
August 27, 2018
How to add a property to an object that doesn't exist in its type?
In case anyone is still wondering return {...apiResponse, D: 123}; More on reddit.com
🌐 r/typescript
6
5
September 28, 2022
Why TS is not allowing me to add properties to an object ?
I think the issue might be that the keys of Person are mixed, could be a string or a number. Your personKeys array holds those keys, but the type checker can't guarantee through that that the intermediate value (when narrowed into a string) will always be assignable into unCompletePerson[key]. If I were to guess why, I think the type checker narrows down unCompletePerson[key] into something that's the intersection of undefined | string and undefined | number, which is just undefined. That probably explains the TS error. Without knowing more about your full lifecycle of the partial person objects, I don't really have any ideas for how to address this. Though I only woke up like 5 min before seeing your post, might just need my coffee. More on reddit.com
🌐 r/typescript
28
0
August 31, 2024
How can I add a key/value pair to a JavaScript object? - Stack Overflow
Here is my object literal: var obj = {key1: value1, key2: value2}; How can I add field key3 with value3 to the object? More on stackoverflow.com
🌐 stackoverflow.com
November 5, 2017
🌐
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 ...
🌐
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 - Each property has a value. firstName is "John", lastName is "Doe", and age is 25. In plain JavaScript, adding a property to an object is as simple as writing person.middleName = "William". However, TypeScript is a statically-typed superset of JavaScript, which means it adds and enforces types to the language.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-add-key-value-pair-to-a-javascript-object
How to add Key-Value pair to a JavaScript Object? - GeeksforGeeks
July 11, 2025 - ... const obj = { Organisation: "GFG" }; const Field = "field"; const Year = "year"; const lang = "lang"; obj[Field] = "CS"; obj[Year] = "2023"; obj[lang] = "English"; console.log(obj); ... In this approach, we are using Object.assign() method to ...
🌐
Alexey Berezin
blog.beraliv.dev › 2021-06-16-append-to-object
Append key-value pair to object type in TypeScript<!-- --> | <!-- -->Alexey Berezin
June 16, 2021 - First of all, we need to add the value by the key. Let's try out https://tsplay.dev/w62Yew: ... But unfortunately we cannot use type U as a value here. Instead we say that we iterate over elements from U – https://tsplay.dev/WP5XJw. ... But this is also not working as U should have the specific type to be a key in an object – PropertyKey.
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript key-value pair
Typescript Key Value Pair | Internal Working and Advantages
May 18, 2023 - It has specific methods that help the user to work over the key-value function. The map. set(key), map. get(key), map. has(Key) are some of the proficient methods used. We will see some examples of this later in this section. We can also store the key-value pair in the Object instance. Just accessing the object values will give the desired result. ... Create a TypeScript Map.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
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".
🌐
Reddit
reddit.com › r/typescript › why ts is not allowing me to add properties to an object ?
r/typescript on Reddit: Why TS is not allowing me to add properties to an object ?
August 31, 2024 -

You may say what's the point. but i'm trying to simplify a bigger situation here. we have a Person type and an object called originalPerson :

type Person = {
    id: number;
    name: string;
    age: number;
    email: string;
};
const originalPerson: Person = {
    id: 1,
    name: "John Doe",
    age: 30,
    email: "john.doe@example.com"
};

Then we have unCompletePerson -I want to populate it with some of person's properties later-

const unCompletePerson: Partial<Person> = {};

Now I want to add all the values that are strings to unCompletePerson

//get keys
const personKeys = Object.keys(originalPerson) as (keyof Person)[];

// Copy properties from `originalPerson` to `updatedPerson`
personKeys.forEach((key) => {
    const value = originalPerson[key];
    // We don't expect any values to be `undefined` in `originalPerson`
   if (typeof value === 'string') unCompletePerson[key] = value 
});

TS says for unCompletePerson[key] : Type 'string' is not assignable to type 'undefined'. please explain like I'm five, why? what's the solution here ?

View code on playground

Thank you

🌐
GeeksforGeeks
geeksforgeeks.org › typescript › how-to-get-an-object-value-by-key-in-typescript
How to Get an Object Value By Key in TypeScript - GeeksforGeeks
July 23, 2025 - In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining.
Top answer
1 of 16
3049

There are two ways to add new properties to an object:

var obj = {
    key1: value1,
    key2: value2
};

Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

A real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();
2 of 16
688

Year 2017 answer: Object.assign()

Object.assign(dest, src1, src2, ...) merges objects.

It overwrites dest with properties and values of (however many) source objects, then returns dest.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Live example

var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});

document.body.innerHTML = JSON.stringify(obj);

Year 2018 answer: object spread operator {...}

obj = {...obj, ...pair, scalar};

From MDN:

It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

Note that Object.assign() triggers setters whereas spread syntax doesn’t.

Live example

It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.

var obj = {key1: "value1", key2: "value2"};
var pair = {key3: "value3"};
var scalar = "value4"
obj = {...obj, ...pair, scalar};

document.body.innerHTML = JSON.stringify(obj);

Year 2019 answer

Object assignment operator +=:

obj += {key3: "value3"};

Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!

Top answer
1 of 2
8

The code in your question is largely correct, here is a full working example:

const profile = {
    "RouteID": "B76F77922EF83A4EE04024921F591A6F",
    "Name": "3019998FALCON",
    "rName": "KILGORE REMOVED"
}

profile["userID"] = "jzket";

// Works everywhere
console.log(profile["userID"]);

// Works, but violates the type information available here
console.log(profile.userID);

You'll notice that the type system will complain about the latter usage, because userID isn't part of the type inferred for profile.

You can either stick with the first example (profile['userID']) or provide a bit more type information:

interface Profile {
    RouteID: string;
    Name: string;
    rName: string;
    userID?: string;
}

const profile: Profile = {
    "RouteID": "B76F77922EF83A4EE04024921F591A6F",
    "Name": "3019998FALCON",
    "rName": "KILGORE REMOVED"
}

profile["userID"] = "jzket";

// Works everywhere
console.log(profile["userID"]);

// Works, but violates the type information available here
console.log(profile.userID);
2 of 2
6

I totally agree with @Fenton. Maybe a little bit better approach is to add a new key / value pair with:

Object.assign like this:

const newProfile = Object.assign(profile, { userID: "jzket" });

Or with Spread Syntax:

const newProfile = ({...profile, userID: "jzket" });

JSFiddle example:

const profile = {
  "ruteID":"B76F77922EF83A4EE04024921F591A6F",
  "Name":"3019998FALCON",
  "rName":"KILGORE REMOVED",
};

// With object assign
const exampleOne = Object.assign(profile, { userID: "jzket" });

// With spread syntax
const exampleTwo = ({...profile, userID: "jzket" })

console.log(exampleOne);
console.log(exampleTwo);

Useful links:

Spread Syntax

Object Assign

🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › add key-value pair to object
How can I add a key-value pair to a JavaScript object? - 30 seconds of code
July 21, 2022 - Last but not least, there's the object spread operator (...). Contrary to previous methods, this one doesn't mutate the original object, but instead returns a new object with the added properties. As expected, the performance of this approach is significantly worse than previous ones, due to the need to create a new object. const obj = { a: 1 }; const newObj = { ...obj, b: 2, c: 3 }; // obj = { a: 1 } // newObj = { a: 1, b: 2, c: 3 } ... Learn how to invert the key-value pairs of an object in JavaScript.
🌐
Medium
medium.com › @ryan_forrester_ › add-key-value-to-object-in-javascript-how-to-guide-30dd2c196033
Add Key Value to Object In JavaScript (How To Guide) | by ryan | Medium
September 10, 2024 - This guide will explore various methods to add key-value pairs to objects in JavaScript and provide practical examples.
🌐
Programiz
programiz.com › javascript › examples › add-key-object
JavaScript Program to Add Key/Value Pair to an Object
// program to add a key/value pair to an object const person = { name: 'Monica', age: 22, gender: 'female' } // add a key/value pair person.height = 5.4; console.log(person);
🌐
Scaler
scaler.com › home › topics › typescript › typescript objects
TypeScript Objects - Scaler Topics
March 7, 2023 - The values will match the typed string exactly. This presents the ideal chance for us to use the index signature. A string may be used to access a JavaScript object (and, by extension, a TypeScript object) and hold a reference to any other JavaScript object. ... Under the 'key' Hello, we store the string Sahil.
🌐
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.