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

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.

主站蜘蛛池模板: 临清市| 西昌市| 固阳县| 石门县| 绥阳县| 阳朔县| 景宁| 康乐县| 台北市| 内黄县| 大连市| 墨脱县| 临安市| 台东市| 通江县| 灵石县| 剑河县| 厦门市| 横山县| 武安市| 东方市| 资溪县| 清苑县| 屏南县| 宣汉县| 页游| 林口县| 三台县| 博客| 正镶白旗| 内乡县| 丹巴县| 邛崃市| 周口市| 商河县| 泰州市| 德兴市| 托克逊县| 南雄市| 柘荣县| 巴楚县|