Add Property to Object in TypeScript

Are you working with TypeScript objects? Then you may be required to add properties to objects. There are various methods to do so.

In this tutorial, I’ll show you several ways to add properties to TypeScript objects, from basic approaches to more advanced techniques for special cases. Let’s dive in!

TypeScript Objects and Properties

TypeScript objects are similar to JavaScript objects, but with the added benefit of static typing. This means we need to be more explicit about the structure of our objects, which ultimately leads to more robust code.

When working with TypeScript objects, you might need to add properties after the object has been created. There are several ways to do this, depending on your specific requirements.

Let me explain a few methods with examples to help you understand better.

Method 1: Add Properties During Object Creation

The simplest way to add properties to a TypeScript object is to include them during the initial object creation.

Here is an example:

// Define an interface for our object
interface Person {
  firstName: string;
  lastName: string;
  age?: number; // Optional property
}

// Create object with all required properties
const person: Person = {
  firstName: "John",
  lastName: "Doe",
  age: 30 // Optional property included
};
console.log(person);

This approach works well when you know all the properties you need upfront, which is often the case in well-planned applications.

I executed the above TypeScript code. You can see the output in the screenshot below:

typescript add property to object

Check out Merge Two Objects in TypeScript

Method 2: Using Type Assertions to Add Properties

If you need to add properties after object creation, one approach is to use type assertions in TypeScript. Here is an example.

interface User {
  id: number;
  name: string;
}

// Create initial object
const user = { id: 1 } as User;

// Add the missing property
user.name = "Jane Smith";

console.log(user); // { id: 1, name: "Jane Smith" }

With this approach, TypeScript trusts that you know what you’re doing when you assert that the incomplete object is of type User. This can be useful during transitional states of an object.

Check out Merge Object Arrays Without Duplicates in TypeScript

Method 3: Using Index Signatures for Dynamic Properties

When you need to add properties dynamically in TypeScript (without knowing their names in advance), you can use index signatures.

Here is the TypeScript code.

interface DynamicObject {
  id: number;
  [key: string]: any; // Index signature
}

const customer: DynamicObject = {
  id: 42
};

// Now we can add any string properties
customer.name = "Alice Johnson";
customer.email = "alice@example.com";
customer.memberSince = new Date();

console.log(customer);
// { id: 42, name: "Alice Johnson", email: "alice@example.com", memberSince: [Date object] }

This approach is perfect for scenarios where you need to accommodate dynamic data, such as user preferences or form data.

You can also see the exact output in the screenshot below:

add property to object typescript

Check out Typescript merge two arrays of objects

Method 4: Extend Interfaces for Added Type Safety

For more complex applications, you might want to extend interfaces to add properties while maintaining type safety:

interface BaseProduct {
  id: number;
  name: string;
}

interface DetailedProduct extends BaseProduct {
  description: string;
  price: number;
}

// Start with a base product
const baseProduct: BaseProduct = {
  id: 123,
  name: "Smartphone"
};

// Create a detailed product with additional properties
const detailedProduct: DetailedProduct = {
  ...baseProduct,
  description: "Latest model with high-resolution camera",
  price: 999.99
};

console.log(detailedProduct);

This approach is elegant when dealing with objects that evolve from a simpler form to a more complex one.

Check out Typescript filter array of objects

Method 5: Using Intersection Types for Combining Properties

Intersection types are powerful when you need to combine multiple types in TypeScript. Here is an example.

interface Address {
  street: string;
  city: string;
  state: string;
  zipCode: string;
}

interface Contact {
  email: string;
  phone: string;
}

// Create a customer that has both address and contact information
type CustomerInfo = Address & Contact;

const customer: CustomerInfo = {
  street: "123 Main St",
  city: "New York",
  state: "NY",
  zipCode: "10001",
  email: "customer@example.com",
  phone: "555-123-4567"
};

console.log(customer);

This pattern is particularly useful when dealing with composable pieces of data that frequently appear together.

Check out Typescript sort array of objects by date descending

Method 6: Using Record Utility Type for Key-Value Pairs

When dealing with collections of key-value pairs, the Record utility type can be very helpful:

// Using Record for a state management store
type UserState = Record<string, any>;

const userStateStore: UserState = {};

// Now we can add any properties
userStateStore.currentUser = { id: 1, name: "John" };
userStateStore.isLoggedIn = true;
userStateStore.sessionStartTime = new Date();

console.log(userStateStore);

This approach works well for state management or configuration objects where properties may change frequently.

Read Typescript map object to another

Method 7: Using the Spread Operator with Type Casting

The spread operator provides a clean way to create new objects with additional properties in TypeScript.

Follow the example below and the full code.

interface Product {
  id: string;
  title: string;
  price: number;
}

const baseProduct: Product = {
  id: "prod-1234",
  title: "Wireless Headphones",
  price: 129.99
};

// Create a new object with additional properties
const productWithDiscount = {
  ...baseProduct,
  discountPercentage: 15,
  salePrice: baseProduct.price * 0.85
} as Product & { discountPercentage: number; salePrice: number };

console.log(productWithDiscount);

This technique creates a new object rather than modifying the existing one, which is often preferred for maintaining immutability.

You can see the exact output in the screenshot below:

typescript add property to type

Read How to push an object into an array in Typescript

Best Practices for Adding Properties to TypeScript Objects

After years of working with TypeScript, I’ve developed these guidelines for adding properties to objects, and you can consider following them.

  1. Define interfaces upfront: Whenever possible, define your interfaces before creating objects to ensure type safety.
  2. Prefer immutability: Instead of modifying existing objects, create new ones with the spread operator.
  3. Be cautious with type assertions: While convenient, excessive use of as can undermine TypeScript’s type safety benefits.
  4. Use optional properties for flexibility: Mark properties with ? if they might not always be present.
  5. Consider partial types for incomplete objects: Use Partial<Type> when working with objects that will be populated gradually.

TypeScript gives us many ways to add properties to objects. The right approach depends on your specific scenario, the level of type safety you need, and whether you prefer mutability or immutability.

In this tutorial, I explained how to add a property to an object in TypeScript using various methods. I hope you found this guide helpful!

Other articles you may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App