- Learn React with TypeScript 3
- Carl Rippon
- 210字
- 2021-06-10 19:16:36
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:
- Let's create a file called product.ts and enter the following interface for a product:
interface Product {
name: string;
unitPrice: number;
}
- 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.
- Implementing VMware Horizon 7(Second Edition)
- 數(shù)據(jù)庫原理及應(yīng)用(Access版)第3版
- PHP 7底層設(shè)計(jì)與源碼實(shí)現(xiàn)
- GeoServer Beginner's Guide(Second Edition)
- Learning Python Data Visualization
- Laravel Design Patterns and Best Practices
- 大話代碼架構(gòu):項(xiàng)目實(shí)戰(zhàn)版
- 軟件開發(fā)中的決策:權(quán)衡與取舍
- Python繪圖指南:分形與數(shù)據(jù)可視化(全彩)
- HTML5/CSS3/JavaScript技術(shù)大全
- 像程序員一樣使用MySQL
- 區(qū)塊鏈原理與技術(shù)應(yīng)用
- 信息安全技術(shù)(第2版)
- 深入解析Java虛擬機(jī)HotSpot
- C# 4.0權(quán)威指南