官术网_书友最值得收藏!

Structuring code into modules

By default, TypeScript generated JavaScript code that executes in what is called the global scope. This means code from one file is automatically available in another file. This in turn means that the functions we implement can overwrite functions in other files if the names are the same, which can cause our applications to break.

Let's look at an example in Visual Studio Code:

  1. Let's create a file called product.ts and enter the following interface for a product:
interface Product {
name: string;
unitPrice: number;
}
  1. Let's create another file, called orderDetail.ts, with the following content:
class OrderDetail {
product: Product;
quantity: number;
getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}

The compiler doesn't give us any complaints. In particular, the reference to the Product interface in the OrderDetail class is able to be resolved, even though it's in a different file. This is because both Product and OrderDetail are in the global scope.

Operating in the global scope is problematic because item names can conflict across different files, and as our code base grows, this is harder to avoid. Modules resolve this issue and help us write well organized and reusable code.

主站蜘蛛池模板: 清河县| 九龙县| 广南县| 宁海县| 边坝县| 星座| 丰城市| 铅山县| 南澳县| 高邮市| 桦南县| 北京市| 宝鸡市| 商城县| 土默特左旗| 嘉定区| 如东县| 房产| 玉环县| 土默特右旗| 紫阳县| 延寿县| 启东市| 泸西县| 霍邱县| 崇文区| 哈尔滨市| 玛曲县| 含山县| 开江县| 曲沃县| 全椒县| 屏南县| 天祝| 尉氏县| 贵港市| 疏勒县| 宁乡县| 连平县| 礼泉县| 五原县|