简单的typescript实战

63 阅读1分钟

用typescript创建一个简单的购物清单应用程序:

item.ts 文件中定义一个商品类和一个购物清单类:

// item.ts
export class Item {
  constructor(public name: string, public price: number, public quantity: number) {}

  getTotalPrice(): number {
    return this.price * this.quantity;
  }
}

export class ShoppingList {
  private items: Item[];

  constructor() {
    this.items = [];
  }

  addItem(item: Item): void {
    this.items.push(item);
  }

  removeItem(index: number): void {
    this.items.splice(index, 1);
  }

  getTotalCost(): number {
    let totalCost = 0;
    for (const item of this.items) {
      totalCost += item.getTotalPrice();
    }
    return totalCost;
  }

  printShoppingList(): void {
    console.log('Shopping List:');
    for (let i = 0; i < this.items.length; i++) {
      console.log(`${i + 1}. ${this.items[i].name} - Quantity: ${this.items[i].quantity}`);
    }
    console.log(`Total Cost: ${this.getTotalCost()}`);
  }
}

index.ts 文件中使用上述定义的类:

// index.ts
import { Item, ShoppingList } from './item';

const shoppingList = new ShoppingList();

const item1 = new Item('Apples', 1.5, 3);
const item2 = new Item('Bread', 2, 2);
const item3 = new Item('Milk', 3, 1);

shoppingList.addItem(item1);
shoppingList.addItem(item2);
shoppingList.addItem(item3);

shoppingList.printShoppingList();

通过以上代码,我们定义了一个 Item 商品类和一个 ShoppingList 购物清单类。在 ShoppingList 类中,我们使用数组来存储购物清单中的商品,并实现了添加、删除和计算购物清单总费用的功能。

index.ts 中,我们创建了一个购物清单实例,并添加了几个商品到清单中。然后,通过调用 printShoppingList 方法,打印了清单中的商品名称、数量以及总费用。

最后在命令行中执行 tsc index.ts 进行编译,然后通过 node index.js 运行生成的 JavaScript 代码。输出结果将会是:

Shopping List: 
1. Apples - Quantity: 3 
2. Bread - Quantity: 2 
3. Milk - Quantity: 1 
Total Cost: 12.5