• 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?

Peter Olson's user avatar

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.

Akash's user avatar

Or all in one go:

Crwth's user avatar

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

jmvtrinidad's user avatar

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

David Gardiner's user avatar

Although the compiler complains it should still output it as you require. However, this will work.

Brandon McConnell's user avatar

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:

Things to be aware of

GreeneCreations's user avatar

One more option do to that is to access the property as a collection:

var obj = {}; obj['prop'] = "value";

Aviw's user avatar

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.

Alex's user avatar

Late but, simple answer

Tobias S.'s user avatar

you can use this :

HamidReza's user avatar

assylias's user avatar

Simplest will be following

Jayant Varshney's user avatar

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 .

ford04's user avatar

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:

LEMUEL  ADANE's user avatar

To guarantee that the type is an Object (i.e. key-value pairs ), use:

bersling's user avatar

It is possible to add a member to an existing object by

Daniel Dietrich's user avatar

The best practice is use safe typing, I recommend you:

Isidro Martínez's user avatar

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.

Imtiaz Shakil Siddique's user avatar

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':

Erlend Robaye's user avatar

To preserve your previous type, temporary cast your object to any

The new dynamic property will only be available when you use the cast:

Andre Vianna's user avatar

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

Nerdroid's user avatar

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.

fregante's user avatar

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:

KushalSeth's user avatar

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:

Danilo Carrabino's user avatar

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:

Jack Punt's user avatar

You can add this declaration to silence the warnings.

Pang's user avatar

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).

Rafał Cieślak's user avatar

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.:

Ciro Santilli OurBigBook.com's user avatar

Then use it

Tung Nguyen's user avatar

Not the answer you're looking for? Browse other questions tagged typescript or ask your own question .

Hot Network Questions

typescript assign property by name

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 .

LogRocket Blog

typescript assign property by name

How to dynamically assign properties to an object in TypeScript

September 5, 2022 4 min read 1262

typescript assign property by name

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.

An error is thrown when dynamically assigning a property to an 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 :

Exploring the literal object type

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.

typescript assign property by name

Over 200k developers use LogRocket to create better digital experiences

typescript assign property by name

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:

Using the Record utility 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:

Dark Background Typescript Playground Showing Map Object No Errors

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.

Dark Background Typescript Playground Showing Constant S With Type Any Indicated By Red Arrow

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 Dashboard Free Trial Banner

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:

Improving mobile design with the latest CSS viewport units

typescript assign property by name

A guide to adding SSR to an existing Vue…

typescript assign property by name

Using Insta for Rust snapshot testing

typescript assign property by name

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:

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.

Typescript adds a property to object

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:

Typescript adds a property to objects dynamically

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:

Typescript add property to object conditionally

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:

Typescript add property to object in array

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:

Typescript add property to object type

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.

Typescript adds a property to objects in the map

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.

Typescript add property to object if exist

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:

Typescript add property to object spread

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.

Typescript add property to object if exists

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.

Typescript add property to object without interface

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:

You may like the following typescript tutorials:

Bijay Kumar

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

avatar

Borislav Hadzhiev

Reading time · 9 min

banner

Photo from Unsplash

Table of Contents #

Add a property to an Object in TypeScript #

To add a property to an object in TypeScript:

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.

book cover

Web Developer

buy me a coffee

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.

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 ❤

Daniel Rosenwasser  (52)

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.

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.

# 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

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

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.

Code snippet on HTML abbr Tag

HTML abbr Tag

Code snippet on How to Pad a String with padStart and padEnd in JavaScript

How to Pad a String with padStart and padEnd in JavaScript

Code snippet on Avoid Empty Class in Vue with Null

Avoid Empty Class in Vue with Null

Code snippet on Fix Text Overlap with CSS white-space

Fix Text Overlap with CSS white-space

Code snippet on How to Check if Object is Empty in JavaScript

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.

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

typescript assign property by name

Get certified by completing a course today!

Subscribe

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

  1. typescript class property name interface Code Example

    typescript assign property by name

  2. typescript

    typescript assign property by name

  3. Asp.net And HTML Css And Web Development: How to Create Typescript Property Class and also

    typescript assign property by name

  4. assign component to variable react typescript type Code Example

    typescript assign property by name

  5. Typescript Property With Question Mark

    typescript assign property by name

  6. Create a React App Using Typescript

    typescript assign property by name

VIDEO

  1. TypeScript

  2. TypeScript 08 Asociation

  3. Flatten array rest/spread property #shorts

  4. Learn Typescript In Arabic 2022

  5. TypeScript Quickly. Lesson 15. Enforcing contracts with interfaces

  6. Mastering TypeScript Class Modifiers: A Comprehensive Guide for Beginners and Pros

COMMENTS

  1. How do I dynamically assign properties to an object in TypeScript?

    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.

  2. How to dynamically assign properties to an object in TypeScript

    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

  3. How to add a property to object in Typescript [With 9 examples]

    Here we will see how we can add properties to objects dynamically in typescript. By using an index signature we can dynamically add properties

  4. How to 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 and add the

  5. Documentation

    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

  6. How to Access Object Properties Dynamically Using Bracket

    Screenshot of Typescript code ... Instead, we will assign the value of the button to the respective property name of the relevant dimensions

  7. Object.assign()

    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

  8. Property accessors

    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

  9. How to Set Dynamic Property Keys with ES6

    With ES6, we can finally create dynamic variable key in the object declaration... ... Bracket notation (string key) me['name']; // samantha // 3.

  10. JavaScript Object 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