Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a new key with a value to an object in TypeScript?

I have a function whose task is to count the price of a product after a discount. However as a result I get objects without this value (totalPrice). Where am I making mistake?

const arrayObj = [
    {
        basePrice: 12,
        discount: 3,
    },
    {
        basePrice: 12,
        discount: 2,
    },
    {
        basePrice: 8,
        discount: 2,
    },
];

interface Product {
    basePrice: number;
    discount: number;
    totalPrice?: number;
}
const countTotalPrice = (products: Product[]): Product[] => {
    const calculateTotalPrice = (
        basePrice: number,
        discount: number,
        totalPrice?: number
    ): void => {
    
        totalPrice = basePrice - discount;
    };

    products.forEach((product) =>
        calculateTotalPrice(
            product.basePrice,
            product.discount,
            product.totalPrice
        )
    );
    return products;
};
console.log(countTotalPrice(arrayObj));
like image 774
Yerba Mate Avatar asked Nov 19 '25 13:11

Yerba Mate


1 Answers

You are not modifying products in your array. You have two options:

  • use products.forEach and pass in a function that modifies a product. Return modified products.
  • use products.map and pass in a function that takes a product and creates new object with additional property, return the result of mapping.

I would argue that 2nd approach is more idiomatic in JS/TS.

const countTotalPrice = (products: Product[]): Product[] => {
  return products.map((product) => 
    ({    // the parentheses are necessary in this position
          // we want object literal, not code block
          ...product,
          totalPrice: product.basePrice - product.discount
    })
  );
}

Playground link

like image 128
Lesiak Avatar answered Nov 21 '25 01:11

Lesiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!