- 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.
- ReSharper Essentials
- Computer Vision for the Web
- 基于Java技術的Web應用開發
- React.js Essentials
- Building Serverless Applications with Python
- Learning Apache Karaf
- Mastering React
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- Building Wireless Sensor Networks Using Arduino
- Learning Nessus for Penetration Testing
- 高效使用Greenplum:入門、進階與數據中臺
- 零基礎學Java第2版
- Learning Cocos2d-JS Game Development
- Ionic3與CodePush初探:支持跨平臺與熱更新的App開發技術
- Python Business Intelligence Cookbook