TypeScript Conditionally Add Property to Object

When working with objects in TypeScript, you may experience cases where you need to conditionally add properties to objects.

In this article, we will explore different methods and best practices for accomplishing this, helping you become more proficient in TypeScript.

Different Method in TypeScript Conditionally Add Property to Object

One of the most common challenges developers experience is adding properties to objects conditionally. Let’s proceed with this topic and explore different methods.

Using the Spread Operator Method

The spread operator (…) in TypeScript enables you to create shallow copies of objects while adding or changing properties conditionally.

Here’s an example code:

const originalObjectSample = { name: "Glenn" };
const conditionValue = true;

const updatedObjectResult = { ...originalObjectSample, ...(conditionValue && { age: 26 }) };
console.log(updatedObjectResult)

Output:

{ name: 'Glenn', age: 26 }

In this example code, the age property will be added to updatedObjectResult only if the condition evaluates to true.

Also read: Javascript conditionally add property to object in an easy way

Using Object.assign() Method

The Object.assign() method is another approach to add properties to objects conditionally:

For example:

const originalObjectValue = { name: "Caren" };
const conditionSample = true;

const updatedObjectResult = Object.assign({}, originalObjectValue, conditionSample ? { age: 27 } : {});
console.log(updatedObjectResult)

Output:

{ name: 'Caren', age: 27 }

This method creates a new object with the properties of updatedObjectResult and adds the age property if the condition is met.

TypeScript Conditional Types

TypeScript also offers conditional types, which can be used to conditionally add properties based on the type of an object.

Here’s an example of conditional types:

type People = { name: string; age?: number };

function addAgeIfNotExists<T extends People>(person: T): T & { age: number } {
  if (!person.age) {
    return { ...person, age: 25 };
  }
  return person as T & { age: number };
}

In this example, the addAgeIfNotExists function adds an age property to a Person object if it does not already exist.

Using TypeScript’s Type Inference

TypeScript’s powerful type inference system can add properties to objects with precision conditionally.

By using segregated unions, you can create types that depend on specific conditions:

For example:

type SquareSample = { kind: "square"; size: number };
type CircleSample = { kind: "circle"; radius: number };

type Shape = SquareSample | CircleSample;

function calculateArea(shape: Shape): number {
  switch (shape.kind) {
    case "square":
      return shape.size ** 2;
    case "circle":
      return Math.PI * shape.radius ** 2;
    default:
      throw new Error("Invalid shape");
  }
}
const square: SquareSample = { kind: "square", size: 5 };
console.log(`The area of the square is: ${calculateArea(square)}`);

const circle: CircleSample = { kind: "circle", radius: 3 };
console.log(`The area of the circle is: ${calculateArea(circle)}`);

In this example, TypeScript speculates the appropriate properties based on the kind property, allowing you to work with objects in a type-safe manner.

FAQs

How can I conditionally add multiple properties to an object in TypeScript?

To conditionally add multiple properties, you can use the spread operator or Object.assign() multiple times, each time adding a various properties based on your conditions.

Can I conditionally add properties to nested objects?

Yes, you can conditionally add properties to nested objects by applying the same principles to the nested objects within the current object.

Are there any TypeScript libraries that simplify conditional property addition?

es, libraries like immer and ts-transformer-keys can offer more advanced techniques for working with objects in TypeScript.

Conclusion

Conditionally adding properties to objects in TypeScript is a powerful method that can enhance the flexibility and readability of your code.

Whether you select to use the spread operator, Object.assign(), TypeScript conditional types, or type inference, understanding these methods will make you a more proficient TypeScript developer.

Leave a Comment