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

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.

主站蜘蛛池模板: 霍山县| 新昌县| 双峰县| 甘泉县| 疏勒县| 大港区| 罗甸县| 金华市| 赤水市| 利辛县| 思茅市| 遂昌县| 瑞丽市| 平江县| 岳普湖县| 荔浦县| 申扎县| 塘沽区| 泰来县| 平南县| 恩施市| 丰都县| 清河县| 常山县| 金溪县| 岳池县| 阿瓦提县| 磴口县| 青龙| 清河县| 绥芬河市| 广宁县| 湛江市| 南充市| 朔州市| 乌兰浩特市| 孙吴县| 孟连| 仁怀市| 安化县| 望奎县|