How can I programmatically add property to object in TypeScript?

In JavaScript, you can do this:

var obj = {};
obj.prop = "value";

However, in TypeScript, this generates an error: “The property ‘prop’ does not exist on value of type '{}'”.

How can I add new properties to an object in TypeScript? I’m looking for a method to handle typescript add property to object.

In TypeScript, assigning a new property to an object without predefined keys can be done using index signatures. Here’s how you can do it naturally, without forcing the object to be of type any:

Define an interface with an index signature to allow dynamic property names. This approach maintains type safety while allowing for dynamic properties:

interface LooseObject {
    [key: string]: any;
}

var obj: LooseObject = {};
obj.prop = "value";
obj.prop2 = 88;

You can also define a more compact form:

var obj: { [k: string]: any } = {};
obj.prop = "value";
obj.prop2 = 88;

You can define an interface that includes both known properties and allows additional dynamic properties:

interface MyType {
    typesafeProp1?: number;
    requiredProp1: string;
    [key: string]: any;
}

var obj: MyType = { requiredProp1: "foo" }; // Valid
obj.typesafeProp1 = "bar"; // Error: typesafeProp1 should be a number
obj.prop = "value";
obj.prop2 = 88;

This approach is useful when your object has a specific type but you need to add additional properties dynamically. For example:

let user: User = new User();
(user as any).otherProperty = 'hello';
// The user object retains its original type and now has the additional property.

This technique allows you to extend an object with extra properties without losing its specific type, which can be helpful when integrating with other sources or libraries.