- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How do I dynamically assign properties to an object in TypeScript?
If I wanted to programatically assign a property to an object in Javascript, I would do it like this:
But in TypeScript, this generates an error:
The property 'prop' does not exist on value of type '{}'
How am I supposed to assign any new property to an object in TypeScript?
- interface DynamicObject { [key: string]: any } const object:DynamicObject; object['key']='Test value' – Emmalex6250 Jul 28, 2022 at 13:47
- You should use what they call declaration merging. Read about it. An example is in passport.js' index.d.ts – Gilbert Nov 5, 2022 at 15:20
29 Answers 29
Index types.
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.
OR to make it compact:
LooseObject can accept fields with any string as key and any type as value.
The real elegance of this solution is that you can include typesafe fields in the interface.
Record<Keys,Type> utility type
Update (August 2020): @transang brought this up 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,
MyType can now be defined by extending Record type
While this answers the Original question, the answer here by @GreeneCreations might give another perspective on how to approach the problem.
- 23 I think this is the best solution now. I think at the time the question was asked index properties like this were not yet implemented in TypeScript. – Peter Olson Jun 8, 2017 at 19:56
- 1 It does make sense when you have dynamic data. If you are receiving dynamic data from API, to build form, and then sending back dynamic values to api, it does make sense. Any is there for a reason, obviously you should strongly type most of stuff which is not dynamic, but in dynamic cases you can't strongly type. – sensei Jun 13, 2019 at 15:03
- 10 now, you can write Record<string, any> , instead of {[key: string]: any} – transang Aug 20, 2020 at 11:00
- It is now recommended to use Record<string, unknown> to avoid using the any type – Mathilda Jan 13, 2022 at 6:37
Or all in one go:
- 110 What's the point of TypeScript if I have to cast so many things to any in order to use it? Just becomes extra noise in my code.. :/ – Ozymandias Jul 22, 2016 at 19:04
- 11 @AjaxLeung You should very rarely cast to any . TypeScript is used to catch (potential) errors at compile time. If you cast to any to mute errors then you lose the power of typing and may as well go back to pure JS. any should ideally only be used if you're importing code for which you cannot write TS definitions or whilst migrating your code from JS to TS – Precastic Jan 19, 2017 at 6:14
- No matter what the best practice or purpose of typescript is, this is the right answer to the question. – M.Arjmandi Jan 26 at 20:19
- @M.Arjmandi - it's really not. The question is asking how you should approach this in terms of typescript. The whole point of typescript is to avoid the annoying side of javascript being dynamic - everything in javascript is effectively cast to any be default. It's objectively not a good answer. – kmars Mar 1 at 6:11
This solution is useful when your object has Specific Type. Like when obtaining the object to other source.

- 11 This is the correct solution for one-off assignments. – soundly_typed Jan 30, 2017 at 6:12
- 2 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. – AlanObject Mar 9, 2019 at 1:17
I tend to put any on the other side i.e. var foo:IFoo = <any>{}; So something like this is still typesafe:
Alternatively you can mark these properties as optional:
Try it online
- 5 +1 for being the only solution that keeps type safety. Just make sure you instanciate all non-optional properties directly after it, to avoid bugs biting you later on. – Aidiakapi Apr 8, 2014 at 15:18
- Does this actually work? After compiling I still have <any>{} in my javascript. – bvs Jan 22, 2015 at 2:10
- 4 I still have <any>{ then you haven't compiled. TypeScript would remove that in its emit – basarat Jan 22, 2015 at 3:06
- 6 These days, var foo: IFoo = {} as any is preferred. The old syntax for typecasting was colliding with TSX (Typescript-ified JSX). – Don Dec 17, 2018 at 20:45
- It's a bit confusing to me, how does <any>{} respect the type of IFoo ? – Minsky Dec 29, 2021 at 19:08
Although the compiler complains it should still output it as you require. However, this will work.

- 12 yes well, this is not really type script way, you loose intellisense. – pregmatch Nov 14, 2018 at 18:54
- Works nice for object with dynamic structure (cannot be defined in an interface) – Camille Nov 25, 2020 at 8:21
- 3 do not use var.. instead use let or const – GorvGoyl May 22, 2021 at 13:37
I'm surprised that none of the answers reference Object.assign since that's the technique I use whenever I think about "composition" in JavaScript.
And it works as expected in TypeScript:
- type safety throughout because you don't need to use the any type at all
- uses TypeScript's aggregate type (as denoted by the & when declaring the type of objectWithAllProps ), which clearly communicates that we're composing a new type on-the-fly (i.e. dynamically)
Things to be aware of
- It can be used in a mutable fashion, or an immutable manner (I demonstrate the immutable way above, which means that existingObject stays untouched and therefore doesn't have an email property. For most functional-style programmers, that's a good thing since the result is the only new change).
- Object.assign works the best when you have flatter objects. If you are combining two nested objects that contain nullable properties, you can end up overwriting truthy values with undefined. If you watch out for the order of the Object.assign arguments, you should be fine.
- For me, in instances where you need to use this to display data it seems to work fine, but when you need to add entries of modified types to an array, this doesn't seem to work too well. I resorted to dynamically composing the object and assigning it in one line, then assigning the dynamic properties in successive lines. This got me most of the way there, so thank you. – Shafiq Jetha Apr 21, 2020 at 13:34
One more option do to that is to access the property as a collection:
var obj = {}; obj['prop'] = "value";

- 7 This is the most concise way. Object.assign(obj, {prop: "value"}) from ES6/ES2015 works, too. – C.W. Mar 28, 2018 at 23:58
You can create new object based on the old object using the spread operator
TypeScript will infer all the fields of the original object and VSCode will do autocompletion, etc.
- nice, but in case you need to use prop2 in e.g. prop3, will be hard to implement – ya_dimon Jun 9, 2020 at 15:56
- 1 Not sure if I follow the statement - there is no prop3 in this example. – Alex Aug 31, 2020 at 8:42
Late but, simple answer

you can use this :

- 3 You don't need this.model = . – wortwart Aug 25, 2020 at 12:16
- this.model = { ...this.model, { newProp: 0 }}; – Joe Bowbeer Dec 8, 2021 at 2:13

Simplest will be following

Here is a special version of Object.assign , that automatically adjusts the variable type with every property change. No need for additional variables, type assertions, explicit types or object copies:
Note: The sample makes use of TS 3.7 assertion functions . The return type of assign is void , unlike Object.assign .

Since you cannot do this:
If your TS compiler and your linter does not strict you, you can write this:
If your TS compiler or linter is strict, another answer would be to typecast:
- 4 This is if 'noImplicitAny: false' on the tsconfig.json – LEMUEL ADANE Apr 3, 2019 at 9:35
- Else you can do GreeneCreations answer. – LEMUEL ADANE Apr 3, 2019 at 9:36
To guarantee that the type is an Object (i.e. key-value pairs ), use:

- This solution worked for me because without the additional type information I was still getting this error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. – Benjamin Smith Mar 25, 2021 at 12:18
It is possible to add a member to an existing object by
- widening the type (read: extend/specialize the interface)
- cast the original object to the extended type
- add the member to the object
The best practice is use safe typing, I recommend you:

Extending @jmvtrinidad solution for Angular,
When working with a already existing typed object, this is how to add new property.
Now if you want to use otherProperty in html side, this is what you'd need:
Angular compiler treats $any() as a cast to the any type just like in TypeScript when a <any> or as any cast is used.

Store any new property on any kind of object by typecasting it to 'any':
Later on you can retrieve it by casting your extended object back to 'any':
- This is totally the correct solution. Lets say you have an object let o : ObjectType; .... later on you can cast o to any (<any>o).newProperty = 'foo'; and it can be retrieve like (<any>o).newProperty. No compiler errors and works like a charm. – Matt Ashley Jul 7, 2016 at 16:24
- this brakes intellisense ... is there any way to this this but to keep intellisense? – pregmatch Nov 14, 2018 at 18:54
To preserve your previous type, temporary cast your object to any
The new dynamic property will only be available when you use the cast:
dynamically assign properties to an object in TypeScript.
to do that You just need to use typescript interfaces like so:
you can use it like that

- 1 I try with your code, but I don't receive any error: pastebin.com/NBvJifzN – pablorsk Apr 3, 2017 at 12:08
- 1 try to initialise the attributes field inside SomeClass and that should fix it public attributes: IType = {}; pastebin.com/3xnu0TnN – Nerdroid Apr 3, 2017 at 23:47
The only solution that is fully type-safe is this one , but is a little wordy and forces you to create multiple objects.
If you must create an empty object first, then pick one of these two solutions. Keep in mind that every time you use as , you're losing safety.
Safer solution
The type of object is safe inside getObject , which means object.a will be of type string | undefined
Short solution
The type of object is not safe inside getObject , which means object.a will be of type string even before its assignment.
Simply do this, and you can add or use any property. (I am using typescript version as "typescript": "~4.5.5" )
Now, you can add any property and use it any where. like
later you can use it as:

I wrote an article tackling this very topic:
Typescript – Enhance an object and its type at runtime
https://tech.xriba.io/2022/03/24/typescript-enhance-an-object-and-its-type-at-runtime/
Maybe you could take inspiration from Typescript concepts such:
- Mapped Types
- Key Remapping via as
- Intersection Types

If you are using Typescript, presumably you want to use the type safety; in which case naked Object and 'any' are counterindicated.
Better to not use Object or {}, but some named type; or you might be using an API with specific types, which you need extend with your own fields. I've found this to work:
You can add this declaration to silence the warnings.

I ran into this problem when trying to do a partial update of an object that was acting as a storage for state.
In this scenario, the best solution would be to use Partial<T> . It makes all properties on the provided type optional using the ? token. Read more about it in a more specific SO topic about making all properties on a type optional .
Here's how I solved it with Partial<T> :
This is similar to what fregante described in their answer, but I wanted to paint a clearer picture for this specific use case (which is common in frontend applications).
Use ES6 Map whenever a map can take truly arbitrary values of fixed type, and optional properties otherwise
I think this is the guideline I'll go for. ES6 map can be done in typescript as mentioned at: ES6 Map in Typescript
The main use case for optional properties are "options" parameters of functions: Using named parameters JavaScript (based on typescript) In that case, we do know in advance the exact list of allowed properties, so the sanest thing to do is to just define an explicit interface, and just make anything that is optional optional with ? as mentioned at: https://stackoverflow.com/a/18444150/895245 to get as much type checking as possible:
And then I'll use Map when it is something that is truly arbitrary (infinitely many possible keys) and of fixed type, e.g.:

Then use it

Not the answer you're looking for? Browse other questions tagged typescript or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Linear Algebra - Linear transformation question
- Questions about bringing spices to New Zealand
- Counting Letters in a String
- Why do many companies reject expired SSL certificates as bugs in bug bounties?
- Create a structure to store student data and display all the records in the array
- Align vertically 2 circuits
- High-side gate driver application schematic
- How to measure the power in mW of a radio signal
- Who owns code in a GitHub organization?
- A plastic tab/tag stuck out of the GE dryer drum gap. Does anyone know what it is, if it is a part of the dryer, and if so how I can fix it?
- Why is there a voltage on my HDMI and coaxial cables?
- What sort of strategies would a medieval military use against a fantasy giant?
- Drywall repair - trying to match texture
- Forced to pay a customs fee for importing a used wedding dress into the Netherlands. Is there a way to avoid paying?
- For the Nozomi from Shinagawa to Osaka, say on a Saturday afternoon, would tickets/seats typically be available - or would you need to book?
- FAA Handbooks Copyrights
- How to print hardware models for humans
- Why are all monasteries human?
- Rolling cube on an infinite chessboard
- Precise control of fraction expression
- Can I tell police to wait and call a lawyer when served with a search warrant?
- Does melting sea ices rises global sea level?
- Why does Mister Mxyzptlk need to have a weakness in the comics?
- Why do we calculate the second half of frequencies in DFT?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

- Start monitoring for free

How to dynamically assign properties to an object in TypeScript
September 5, 2022 4 min read 1262

Consider the following example of TypeScript code:
This seemingly harmless piece of code throws a TypeScript error on dynamically assigning name to the organization object.

See this example in the TypeScript Playground .
The source of confusion, which is perhaps rightly justified if you’re a TypeScript beginner, is: how could something that seems so simple be such a problem in TypeScript?
The TL;DR of it all is that, if you cannot define the variable type at declaration time, you can use the Record utility type or an object index signature to solve this. But in this post, we’ll go through the problem itself and work toward a solution that should work in most cases.
Jump ahead:
Understanding the problem with dynamically assigning properties to objects
Solution 1: explicitly type the object at declaration time, solution 2: use an object index signature, solution 3: use the record utility type, solution 4: use the map data type, solution 5: consider an optional object property.
Generally speaking, TypeScript determines the type of a variable when it is declared, and this determined type doesn’t change, i.e., it stays the same all through your application.
There are exceptions to this rule, such as when considering type narrowing or working with the any type, but this is a general rule to remember otherwise.
In the earlier example, the organization object is declared as follows:
There is no explicit type assigned to the organization variable, so TypeScript infers a type of organization based on the declaration to be {} , i.e., the literal empty object.
For example, if you add a type alias, you can explore the type of organization :

See this in the TypeScript Playground .
When you then try to reference the name prop on this empty object literal:
TypeScript yells.
Property ‘name’ does not exist on type ‘ {} ‘
When you understand the issue, the error does seem appropriate.
Let’s fix this.
Resolving the problem
There are numerous ways you can resolve the TypeScript error here. Let’s consider these:
This is the easiest solution to reason through. At the time you declare the object, go ahead and type it. Furthermore, assign it all the relevant values.
This eliminates any surprises. You’re clearly stating what this object type is and rightly declaring all relevant properties when you create the object.

Over 200k developers use LogRocket to create better digital experiences

However, this is not always feasible if the object properties must be added dynamically , which is why we’re all here.
Occasionally, the properties of the object truly need to be added at a time after they’ve been declared. In this case, you can use the object index signature, as follows:
At the time the organization variable is declared, you can go ahead and explicitly type it to the following {[key: string] : string} .
To explain the syntax further, you might be used to object types having fixed property types:
However, you can also substitute name for a “variable type”.
For example, if you want to define any string property on obj :
Note that the syntax is similar to how you’d use a variable object property in standard JavaScript:
The TypeScript equivalent is called an object index signature. Moreover, note that you could type key with other primitives:
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. The solution here is quite concise as shown below:
Instead of using a type alias, you can also inline the type:

Now, a Map object is a fundamentally different data structure from an object , but for completeness, you could eliminate this problem if you were using a Map .
Consider the starting example rewritten to use a Map object:

See this in the TypeScript playground .
This seems like a great solution at first, but the caveat is your Map object is weakly typed. You can access a nonexisting property and get no warnings at all:
See the TypeScript playground .
This is unlike the standard object.

And if you’re not sure what the keys or values are, be safe by representing this at the type level:
This solution won’t always be possible, but if you know know the name of the property to be dynamically assigned, you can go ahead to optionally provide this when initializing the object as shown below:
If you don’t like the idea of using optional properties, you can be more explicit with your typing as shown below:
Apart from primitives, the most common types you’ll have to deal with are likely object types.
In cases where you need 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.
If you’d like to read more on this subject, feel free to check out my cheatsheet on the seven most-asked TypeScript questions on Stack Overflow, or tweet me any questions . Cheers!
LogRocket : Full visibility into your web and mobile apps

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.
Share this:
- Uncategorized
- #typescript
Improving mobile design with the latest CSS viewport units

A guide to adding SSR to an existing Vue…

Using Insta for Rust snapshot testing

2 Replies to “How to dynamically assign properties to an object in…”
I know this is explicitly for TypeScript, and I think type declarations should always be first. But in general, you can also use a Map object. If it’s really meant to by dynamic, might as well utilize the power of Map.
Great suggestion (updated the article). It’s worth mentioning the weak typing you get by default i.e., with respect to Typescript.
Leave a Reply Cancel reply
How to add a property to object in Typescript [With 9 examples]
In this Typescript tutorial, we will see how we can add a property to an object in Typescript. Also, we will see different examples to add a property object in typescript:
- How to add a property to an object in a typescript
- How to add a property to an object dynamically in typescript
- How to add a property to an object conditionally in typescript
- How to add a property to an object in an array in typescript
- How to add a property to object type in typescript
- How to add a property to object if not null in typescript
- How to add a property to object spread in typescript
- How to add a property to object if exists in typescript
- How to add a property to object without interface in typescript
- How to add a property to object in map in typescript
Table of Contents
Typescript adds a property to object
Here we will see a simple example of how we can add a property to objects in typescript.
For example, we will see how we can add the age property and then both name and age property to the object in typescript.
In the code editor, create a new file objectProperties.ts, then write the below code.
To compile the code and run the below command and you can see the result in the console.

This is an example of Typescript adding a property to an object.
Read Data types in typescript with examples
Typescript adds a property to objects dynamically
Here we will see how we can add properties to objects dynamically in typescript.
By using an index signature we can dynamically add properties to an object, for example, const object: {[key: string]: any} = {} . Index signature is used when a user doesn’t have any idea about all the names of the type’s properties and the type of their values in advance.
Let’s see an example, so, in the objectProperties.ts file write the below code:

This is an example of Typescript adds a property to objects dynamically.
Typescript add property to object conditionally
Here we will see how we can add property conditionally to an object in typescript.
For example, we will use && operator and spread operator, to add a property to an object conditionally in typescript.
Whereas the spread operator combines the properties of the destination object with the properties of the object being applied to, and if the origin object is null, no properties are added.
Let’s see the example, so, in the objectProperties.ts file write the below code:

This is an example of Typescript add property to object conditionally.
Read Typescript type alias
Typescript adds a property to objects in an array
Here we will see how we can add a property to an object in an array in typescript
For example, we will create an Employee type as an array, this array will accept properties, i.e. name and age. So we will create and add two objects to an array, one object will contain only name properties, and age property we will add later. Then 2nd object contains both properties.
The objectProperties.ts file contains the below code:

This is an example of Typescript add property to object in array.
Typescript adds a property to object type
Here we will see how to add a property to object type in typescript.
For example, we will create an object type, then based on the condition we will add a property to it in typescript.
In the objectProperties.ts file write the below code:

This is an example of Typescript add property to object type.
Read Typescript array concatenation
Typescript adds a property to objects in the map
Here we will see how we can add a property to objects using map() in typescript.
For example, we will map each object in an array, and then we will add the property to objects in typescript.
In the typescript.ts file, write the below code:
To compile the below code and run the below command and you can see the result in the console.

This is an example of Typescript adds a property to objects in the map.
Typescript add property to object if not null
Here we will see an example if the object is not null, then we will add the property to object.
For example, we will create an object, and we will check if the object is not null, then it will add the properties to it.
To compile the code and run the below command, and you can see the result in the console.

This is an example of Typescript add property to object if not null.
Read How to reverse an array in Typescript
Typescript add property to object spread
Here we will see an example how to add property to object using spread operator in typescript.
For example, we will define an object, then we define a new object, and with the help of spread operator we add the properties of the new object to the original object.
In the objectProperties.ts file, write the below code:

This is an example of Typescript add property to object spread.
Typescript add property to object if exists
Here we will see an example of how to add properties to object if it exists using typescript.
For example, we will define an employee object type, then we will create a function to check object exist or not, if exist, then we will add properties, not, then it will return object does not exist.

This is an example of Typescript add property to object if exists.
Read Typescript sort array
Typescript add property to object without interface
Here we will see how we can add property to object without interface in typescript.
For example, we will first define employee object type using type alias, then we will add properties to it.
In the objectProperties.ts, write the below code:
To compile the code and run the below command, you can see the result in the console.

This is an example of Typescript add property to object without interface.
In this typescript tutorial, we saw how we can add properties to an object in different scenario. So here are the scenario we covered:
- typescript add a property to object
- typescript add property to object dynamically
- typescript add property to object conditionally
- typescript add property to object in array
- typescript add property to object type
- typescript add property to object if not null
- typescript add property to object spread
- typescript add property to object if exists
- typescript add property to object without interface
- typescript add property to object in map
You may like the following typescript tutorials:
- Typescript array
- Typescript filter array
- Typescript Identifiers and Keywords
- Typescript type annotation
I am Bijay a Microsoft MVP (8 times – My MVP Profile ) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com
How to Add a property to an Object in TypeScript

Borislav Hadzhiev
Reading time · 9 min

Photo from Unsplash
Table of Contents #
- Add a property to an Object in TypeScript
- Dynamically add Properties to an Object in TypeScript
- Set an Object's property name from a Variable in TypeScript
- Constructing the object's property name from multiple variables
- Using Object.assign() in TypeScript
Add a property to an Object in TypeScript #
To add a property to an object in TypeScript:
- Mark the property on the interface or type as optional.
- Use the interface to type the object.
- Add the property to the object.
We set the age property on the Person interface to optional .
Now you can initialize the object without the property and set it later on.
If you try to assign a non-numeric value to the age property, you'd get an error.
Add any property to an object in TypeScript #
You can use the Record utility type to add any property of any type to an object.
The Record utility type allows us to enforce the type of an object's values in TypeScript, e.g. type Animal = Record<string, string> .
We used a type of any for the values and a type of string for the keys in the object.
This is very broad and allows us to add any property of any type to the object.
Add any property but type key-value pairs you know in advance #
You can specify the properties and the types in an object that you know about and use the Record utility type to allow the user to add other properties.
The interface we created requires the name and age properties but also extends a type that allows any string properties with values of any type.
This is better than just using the Record utility type with string keys and any values because we get type safety when it comes to the properties we explicitly specified.
Setting a property to the incorrect type causes an error because we've already declared the name property to be of type string in the Animal interface.
Dynamically add Properties to an Object in TypeScript #
Use an index signature to dynamically add properties to an object.
Index signatures are used when we don't know all of the names of a type's properties and the type of their values ahead of time.
The {[key: string]: any} syntax is an index signature in TypeScript and is used when we don't know all the names of a type's properties and the shape of the values ahead of time.
You might also see the index signature {[key: string]: string} in examples. It represents a key-value structure that when indexed with a string returns a value of type string .
Explicitly typing specific properties #
If the value of the string keys were set to any in the index signature, you could add properties to the object of any type, since anything is more specific than any .
This is a good way to narrow down the type of some of the properties that you know ahead of time.
For example, if I try to set the age property to a string , the type checker would throw an error because it expects a number .
We've set the age property to have a type of number , so the type checker helps us spot an error in our application.
Using a union to dynamically add properties to an object #
You can also use a union type to dynamically add properties to an object.
The keys in the object can either have a type of string or number .
Both types are allowed and you can use the union | syntax to include as many types as necessary.
If we try to set a property with a different value on the object, we'd get an error.
Dynamically adding properties to an object with the Record type #
The Record utility type constructs an object type whose keys and values are of a specified type.
We typed the object above to have keys of type string and values of type any .
If you know the type of some of the values ahead of time, specify them in an interface for better type safety.
The interface EmployeeData extends from the Record constructed type with string keys and any type values.
If we try to set the role , salary or color properties to an incompatible type, we'd get an error.
Set an Object's property name from a Variable in TypeScript #
Use computed property names to set an object's property name from a variable in TypeScript.
We set an object's property name from a variable using computed properties.
Here is an example that uses a function.
Constructing the object's property name from multiple variables #
The expression between the square brackets gets evaluated, so you could construct the object's property name by using multiple variables or concatenating strings.
You can also use a template literal.
But notice that TypeScript was not able to type the property in the object as name and instead typed it as a more generic index signature of [x: string] (any string property).
If you are sure about the value the expression will evaluate to, use a type assertion .
Now the object is typed correctly and we can still use the dynamic nature of the computed property names feature.
Using Object.assign() in TypeScript #
To use the Object.assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects.
The method will copy the properties from the source objects to the target object.
We used the Object.assign method to merge two source objects into a target object.
The next parameters are source objects - objects containing the properties you want to apply to the target .
Caveats around using an existing object as the target #
In the example, we passed an empty object as the target because you should generally avoid mutating objects as it introduces confusion.
For example, we could've passed obj1 as the target and obj2 as the source.
Note that the target object is changed in place.
This is especially problematic when using TypeScript because obj1 was changed in place but its type is still {name: string} , even though the object contains a country property as well.
The return type of Object.assign in TypeScript #
TypeScript uses an intersection type to type the return value of the Object.assign() method.
In other words, the return value has a type that has all of the members of all of the objects you passed to the Object.assign() method.
The latter object wins #
When you use the Object.assign() method with objects that have the same properties, the properties are overwritten by objects that come later in the parameter list.
Both of the objects in the example have a name property, so the object that is passed later in the parameters order wins.
An alternative to using Object.assign #
You should also consider using the spread syntax (...) as a replacement for Object.assign() .
The spread syntax (...) unpacks the properties of the objects into a new object.
This is generally a better approach because you can't shoot yourself in the foot by forgetting to provide an empty object as the first parameter of the Object.assign() method.
You can unpack as many objects as necessary into a new object and if two objects have the same property, the object that comes later wins.
Both of the objects have a name property, so the latter object wins.

Web Developer

Copyright © 2023 Borislav Hadzhiev
Was this page helpful?

Object Types
In JavaScript, the fundamental way that we group and pass around data is through objects. In TypeScript, we represent those through object types .
As we’ve seen, they can be anonymous:
or they can be named by using either an interface
or a type alias.
In all three examples above, we’ve written functions that take objects that contain the property name (which must be a string ) and age (which must be a number ).
Property Modifiers
Each property in an object type can specify a couple of things: the type, whether the property is optional, and whether the property can be written to.
Optional Properties
Much of the time, we’ll find ourselves dealing with objects that might have a property set. In those cases, we can mark those properties as optional by adding a question mark ( ? ) to the end of their names.
In this example, both xPos and yPos are considered optional. We can choose to provide either of them, so every call above to paintShape is valid. All optionality really says is that if the property is set, it better have a specific type.
We can also read from those properties - but when we do under strictNullChecks , TypeScript will tell us they’re potentially undefined .
In JavaScript, even if the property has never been set, we can still access it - it’s just going to give us the value undefined . We can just handle undefined specially.
Note that this pattern of setting defaults for unspecified values is so common that JavaScript has syntax to support it.
Here we used a destructuring pattern for paintShape ’s parameter, and provided default values for xPos and yPos . Now xPos and yPos are both definitely present within the body of paintShape , but optional for any callers to paintShape .
Note that there is currently no way to place type annotations within destructuring patterns. This is because the following syntax already means something different in JavaScript.
In an object destructuring pattern, shape: Shape means “grab the property shape and redefine it locally as a variable named Shape . Likewise xPos: number creates a variable named number whose value is based on the parameter’s xPos .
Using mapping modifiers , you can remove optional attributes.
readonly Properties
Properties can also be marked as readonly for TypeScript. While it won’t change any behavior at runtime, a property marked as readonly can’t be written to during type-checking.
Using the readonly modifier doesn’t necessarily imply that a value is totally immutable - or in other words, that its internal contents can’t be changed. It just means the property itself can’t be re-written to.
It’s important to manage expectations of what readonly implies. It’s useful to signal intent during development time for TypeScript on how an object should be used. TypeScript doesn’t factor in whether properties on two types are readonly when checking whether those types are compatible, so readonly properties can also change via aliasing.
Using mapping modifiers , you can remove readonly attributes.
Index Signatures
Sometimes you don’t know all the names of a type’s properties ahead of time, but you do know the shape of the values.
In those cases you can use an index signature to describe the types of possible values, for example:
Above, we have a StringArray interface which has an index signature. This index signature states that when a StringArray is indexed with a number , it will return a string .
Only some types are allowed for index signature properties: string , number , symbol , template string patterns, and union types consisting only of these.
It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number , JavaScript will actually convert that to a string before indexing into an object. That means that indexing with 100 (a number ) is the same thing as indexing with "100" (a string ), so the two need to be consistent.
While string index signatures are a powerful way to describe the “dictionary” pattern, they also enforce that all properties match their return type. This is because a string index declares that obj.property is also available as obj["property"] . In the following example, name ’s type does not match the string index’s type, and the type checker gives an error:
However, properties of different types are acceptable if the index signature is a union of the property types:
Finally, you can make index signatures readonly in order to prevent assignment to their indices:
You can’t set myArray[2] because the index signature is readonly .
Extending Types
It’s pretty common to have types that might be more specific versions of other types. For example, we might have a BasicAddress type that describes the fields necessary for sending letters and packages in the U.S.
In some situations that’s enough, but addresses often have a unit number associated with them if the building at an address has multiple units. We can then describe an AddressWithUnit .
This does the job, but the downside here is that we had to repeat all the other fields from BasicAddress when our changes were purely additive. Instead, we can extend the original BasicAddress type and just add the new fields that are unique to AddressWithUnit .
The extends keyword on an interface allows us to effectively copy members from other named types, and add whatever new members we want. This can be useful for cutting down the amount of type declaration boilerplate we have to write, and for signaling intent that several different declarations of the same property might be related. For example, AddressWithUnit didn’t need to repeat the street property, and because street originates from BasicAddress , a reader will know that those two types are related in some way.
interface s can also extend from multiple types.
Intersection Types
interface s allowed us to build up new types from other types by extending them. TypeScript provides another construct called intersection types that is mainly used to combine existing object types.
An intersection type is defined using the & operator.
Here, we’ve intersected Colorful and Circle to produce a new type that has all the members of Colorful and Circle .
Interfaces vs. Intersections
We just looked at two ways to combine types which are similar, but are actually subtly different. With interfaces, we could use an extends clause to extend from other types, and we were able to do something similar with intersections and name the result with a type alias. The principle difference between the two is how conflicts are handled, and that difference is typically one of the main reasons why you’d pick one over the other between an interface and a type alias of an intersection type.
Generic Object Types
Let’s imagine a Box type that can contain any value - string s, number s, Giraffe s, whatever.
Right now, the contents property is typed as any , which works, but can lead to accidents down the line.
We could instead use unknown , but that would mean that in cases where we already know the type of contents , we’d need to do precautionary checks, or use error-prone type assertions.
One type safe approach would be to instead scaffold out different Box types for every type of contents .
But that means we’ll have to create different functions, or overloads of functions, to operate on these types.
That’s a lot of boilerplate. Moreover, we might later need to introduce new types and overloads. This is frustrating, since our box types and overloads are all effectively the same.
Instead, we can make a generic Box type which declares a type parameter .
You might read this as “A Box of Type is something whose contents have type Type ”. Later on, when we refer to Box , we have to give a type argument in place of Type .
Think of Box as a template for a real type, where Type is a placeholder that will get replaced with some other type. When TypeScript sees Box<string> , it will replace every instance of Type in Box<Type> with string , and end up working with something like { contents: string } . In other words, Box<string> and our earlier StringBox work identically.
Box is reusable in that Type can be substituted with anything. That means that when we need a box for a new type, we don’t need to declare a new Box type at all (though we certainly could if we wanted to).
This also means that we can avoid overloads entirely by instead using generic functions .
It is worth noting that type aliases can also be generic. We could have defined our new Box<Type> interface, which was:
by using a type alias instead:
Since type aliases, unlike interfaces, can describe more than just object types, we can also use them to write other kinds of generic helper types.
We’ll circle back to type aliases in just a little bit.
The Array Type
Generic object types are often some sort of container type that work independently of the type of elements they contain. It’s ideal for data structures to work this way so that they’re re-usable across different data types.
It turns out we’ve been working with a type just like that throughout this handbook: the Array type. Whenever we write out types like number[] or string[] , that’s really just a shorthand for Array<number> and Array<string> .
Much like the Box type above, Array itself is a generic type.
Modern JavaScript also provides other data structures which are generic, like Map<K, V> , Set<T> , and Promise<T> . All this really means is that because of how Map , Set , and Promise behave, they can work with any sets of types.
The ReadonlyArray Type
The ReadonlyArray is a special type that describes arrays that shouldn’t be changed.
Much like the readonly modifier for properties, it’s mainly a tool we can use for intent. When we see a function that returns ReadonlyArray s, it tells us we’re not meant to change the contents at all, and when we see a function that consumes ReadonlyArray s, it tells us that we can pass any array into that function without worrying that it will change its contents.
Unlike Array , there isn’t a ReadonlyArray constructor that we can use.
Instead, we can assign regular Array s to ReadonlyArray s.
Just as TypeScript provides a shorthand syntax for Array<Type> with Type[] , it also provides a shorthand syntax for ReadonlyArray<Type> with readonly Type[] .
One last thing to note is that unlike the readonly property modifier, assignability isn’t bidirectional between regular Array s and ReadonlyArray s.
Tuple Types
A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.
Here, StringNumberPair is a tuple type of string and number . Like ReadonlyArray , it has no representation at runtime, but is significant to TypeScript. To the type system, StringNumberPair describes arrays whose 0 index contains a string and whose 1 index contains a number .
If we try to index past the number of elements, we’ll get an error.
We can also destructure tuples using JavaScript’s array destructuring.
Tuple types are useful in heavily convention-based APIs, where each element’s meaning is “obvious”. This gives us flexibility in whatever we want to name our variables when we destructure them. In the above example, we were able to name elements 0 and 1 to whatever we wanted. However, since not every user holds the same view of what’s obvious, it may be worth reconsidering whether using objects with descriptive property names may be better for your API.
Other than those length checks, simple tuple types like these are equivalent to types which are versions of Array s that declare properties for specific indexes, and that declare length with a numeric literal type.
Another thing you may be interested in is that tuples can have optional properties by writing out a question mark ( ? after an element’s type). Optional tuple elements can only come at the end, and also affect the type of length .
Tuples can also have rest elements, which have to be an array/tuple type.
- StringNumberBooleans describes a tuple whose first two elements are string and number respectively, but which may have any number of boolean s following.
- StringBooleansNumber describes a tuple whose first element is string and then any number of boolean s and ending with a number .
- BooleansStringNumber describes a tuple whose starting elements are any number of boolean s and ending with a string then a number .
A tuple with a rest element has no set “length” - it only has a set of well-known elements in different positions.
Why might optional and rest elements be useful? Well, it allows TypeScript to correspond tuples with parameter lists. Tuples types can be used in rest parameters and arguments , so that the following:
is basically equivalent to:
This is handy when you want to take a variable number of arguments with a rest parameter, and you need a minimum number of elements, but you don’t want to introduce intermediate variables.
readonly Tuple Types
One final note about tuple types - tuples types have readonly variants, and can be specified by sticking a readonly modifier in front of them - just like with array shorthand syntax.
As you might expect, writing to any property of a readonly tuple isn’t allowed in TypeScript.
Tuples tend to be created and left un-modified in most code, so annotating types as readonly tuples when possible is a good default. This is also important given that array literals with const assertions will be inferred with readonly tuple types.
Here, distanceFromOrigin never modifies its elements, but expects a mutable tuple. Since point ’s type was inferred as readonly [3, 4] , it won’t be compatible with [number, number] since that type can’t guarantee point ’s elements won’t be mutated.
More on Functions
Learn about how Functions work in TypeScript.
Creating Types from Types
An overview of the ways in which you can create more types from existing types.
The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤
Last updated: Mar 01, 2023
How to Access Object Properties Dynamically Using Bracket Notation in Typescript
Nader Al-Shamma
18 Sep 2019 | 5 min read
Typescript Playground
Javascript allows you to access the properties of an object using dot notation or bracket notation . The latter can be quite useful if you want to search for a property’s values dynamically.
For example, let’s say we are building a video page for a video website and our users want buttons to resize the given video for their convenience. As the page loads, we fetch the video metadata from the server which includes the link to the video and a selection of available sizes.
We want to associates a button to each possible dimension for the given video. One option is to hard code each object containing the dimensions to a different callback function. Then assign each function to the onclick event of their respective buttons. The result will be three hardcoded onclick callbacks, one for each button and video.
Instead, we will assign the value of the button to the respective property name of the relevant dimensions. When we click on a button, triggering our callback function, we can get the given event’s target value and use it as a property accessor. For example:
On the face of it, recreating this functionality with Typescript should be simple.
However, attempting to access the property using its name, in the same way, will result in as error:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type...
Note, it is important to remember that simply accessing the property using a string accessor, e.g videos['large'] will work but we want to access properties dynamically.
To achieve the same functionality in typescript, we need to make use of the languages’ Index type using the keyof keyword. Index types tell the compiler that the given property or variable is a key representing a publicly accessible property name of a given type. With the keyof keyword we can cast a given value to an Index type or set a variable to the property name an object. In both cases, this is contingent on the value matching a publicly accessible property name of the given object’s type. For more information on Index types and the keyof keyword, check out the Typescript documentation.
Knowing this, we can create the same functionality using Typescript:
We can take this a step further and use Typescript generics to create a function that returns a given object.
This function infers the type of the object T and casts the property name to the key type K , returning the property of the object using the given key T[K] . The original source and a detail explanation of the function can be found in the Typescript documentation .
In conclusion, the ability to access properties via their name and bracket notation is a powerful and flexible feature of Javascript. As demonstrated in the example above, it allows us to work dynamically with objects. Typescript is a superset of javascript that offers static type checking at compile time. This is powerful feature that helps us to build robust apps using Typescript. This, however, means that we need to play by the compilers rules. In this case it means ensuring that we tell the compiler that the dynamic value we are using to access an object’s property, using bracket notation, is actually an index type of the object. We say that this can be achieved by casting the given value using the keyof keyword.
- Skip to main content
- Skip to search
- Skip to select language
- Get MDN Plus
- English (US)
Property accessors
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Description
One can think of an object as an associative array (a.k.a. map , dictionary , hash , lookup table ). The keys in this array are the names of the object's properties .
There are two ways to access properties: dot notation and bracket notation .
Dot notation
In the object.propertyName syntax, the propertyName must be a valid JavaScript identifier which can also be a reserved word . For example, object.$1 is valid, while object.1 is not.
Here, the method named createElement is retrieved from document and is called.
If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.
Bracket notation
In the object[expression] syntax, the expression should evaluate to a string or Symbol that represents the property's name. So, it can be any string literal, for example, including '1foo' , '!bar!' , or even ' ' (a space).
This does the exact same thing as the previous example.
A space before bracket notation is allowed.
Passing expressions that evaluate to property name will do the same thing as directly passing the property name.
However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to object injection attacks .
Property names
Property names are string or Symbol . Any other value, including a number, is coerced to a string. This outputs 'value' , since 1 is coerced into '1' .
This also outputs 'value' , since both foo and bar are converted to the same string.
Method binding
It's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a Function instance as its value).
A method is not bound to the object that it is a property of. Specifically, this is not fixed in a method and does not necessarily refer to the object containing the method. Instead, this is "passed" by the function call. See the reference for this .
Bracket notation vs. eval()
JavaScript novices often make the mistake of using eval() where the bracket notation can be used instead.
For example, the following syntax is often seen in many scripts.
eval() is slow and should be avoided whenever possible. Also, strFormControl would have to hold an identifier, which is not required for names and id s of form controls. It is better to use bracket notation instead:
Specifications
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Object.defineProperty()
- Optional chaining
# How to Set Dynamic Property Keys with ES6 🎉
Previously, we had to do 2 steps - create the object literal and then use the bracket notation. With ES6, you can now directly use a variable as your property key in your object literal. YAY! 👏
- The 3 ways to access the object value
- How to Access Object Value With Emoji Keys
# The 3 ways to access the object value
We can output the object value by passing in the appropriate key. Because I used emoji as the key in my example, it's a bit tricky. So let's look at a easier example.
# How to Access Object Value With Emoji Keys
Alright back to our emoji example. Let's take a look at the output.
Unfortunately, when you're using an Emoji as a key, you won't be able to use the dot notation. You're limited to the Bracket Notation.
# Resources
- Share to Twitter Twitter
- Share to Facebook Facebook
- Share to LinkedIn LinkedIn
- Share to Reddit Reddit
- Share to Hacker News Hacker News
- Email Email
Related Tidbits
Classes in javascript, trick to adding string and number in javascript, javascript module cheatsheet, 3 ways to set default value in javascript, fresh tidbits.

HTML abbr Tag

How to Pad a String with padStart and padEnd in JavaScript

Avoid Empty Class in Vue with Null

Fix Text Overlap with CSS white-space

How to Check if Object is Empty in JavaScript
JS Tutorial
Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript object properties.
Properties are the most important part of any JavaScript object.
JavaScript Properties
Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.
Accessing JavaScript Properties
The syntax for accessing the property of an object is:
The expression must evaluate to a property name.
Advertisement
JavaScript for...in Loop
The JavaScript for...in statement loops through the properties of an object.
The block of code inside of the for...in loop will be executed once for each property.
Looping through the properties of an object:
Adding New Properties
You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:
Deleting Properties
The delete keyword deletes a property from an object:
or delete person["age"];
The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect on variables or functions.
Nested Objects
Values in an object can be another object:
You can access nested objects using the dot notation or the bracket notation:
Nested Arrays and Objects
Values in objects can be arrays, and values in arrays can be objects:
To access arrays inside arrays, use a for-in loop for each array:
Property Attributes
All properties have a name. In addition they also have a value.
The value is one of the property's attributes.
Other attributes are: enumerable, configurable, and writable.
These attributes define how the property can be accessed (is it readable?, is it writable?)
In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
Prototype Properties
JavaScript objects inherit the properties of their prototype.
The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.

IMAGES
VIDEO
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.
This is the easiest solution to reason through. At the time you declare the object, go ahead and type it. Furthermore, assign it all the
Here we will see how we can add properties to objects dynamically in typescript. By using an index signature we can dynamically add properties
To add a property to an object in TypeScript, mark the property on the interface or type as optional. Use the interface to type the object and add the
function greet ( person : { name : string; age : number }) { ... In JavaScript, even if the property has never been set, we can still access it - it's just
Screenshot of Typescript code ... Instead, we will assign the value of the button to the respective property name of the relevant dimensions
The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and
In the object[expression] syntax, the expression should evaluate to a string or Symbol that represents the property's name. So, it can be any
With ES6, we can finally create dynamic variable key in the object declaration... ... Bracket notation (string key) me['name']; // samantha // 3.
You can add new properties to an existing object by simply giving it a value. Assume that the person object already exists - you can then give it new properties