如何在TypeScript中向对象添加一个带有值的新键?

3
我有一个函数,其任务是计算折扣后产品的价格。然而我得到的结果是没有这个值(totalPrice)的对象。我在哪里犯了错误?
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));
3个回答

4

您没有修改数组中的产品。

  • 使用products.forEach并传递一个修改产品的函数。返回修改后的产品。
  • 使用products.map并传递一个将产品作为参数并创建具有附加属性的新对象的函数,返回映射结果。

我认为在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 链接


1

试一下这个

const countTotalPrice = (products: Product[]): Product[] => {
const calculateTotalPrice = (
 p:Product 
): void => {
    

    p.totalPrice = p.basePrice -p. discount;
};

products.forEach((product) =>
    calculateTotalPrice(
        product
    )
);
return products;
};

与其仅仅发布一个新的代码片段,你应该解释一下原始帖子中的代码有什么问题,以及你的代码如何修复它。 - Jeppe

1
您可以使用 Array.prototype.map() 结合 解构赋值 来实现:
interface Product {
  basePrice: number;
  discount: number;
  totalPrice?: number;
}

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

const countTotalPrice = (products: Product[]): Product[] =>
  products.map((p) => ({
    ...p,
    totalPrice: p.basePrice - p.discount,
  }));

没有使用TypeScript的代码示例:

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

const countTotalPrice = (products) =>
  products.map((p) => ({
    ...p,
    totalPrice: p.basePrice - p.discount,
  }))

console.log(countTotalPrice(arrayObj))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接