- Learn React with TypeScript 3
- Carl Rippon
- 256字
- 2021-06-10 19:16:31
Catching coding errors early
The type information helps the TypeScript compiler catch bugs and typos before our users run into them. In code editors such as Visual Studio Code, a mistake is underlined in red immediately after the user has gone wrong. As an example, create a file called utils.js and paste in the following code, which calculates the total price on an order line:
function calculateTotalPrice(product, quantity, discount) {
var priceWithoutDiscount = product.price * quantity;
var discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
There is a bug in the code that might be difficult for us to spot. If we open the file in Visual Studio Code, no errors are highlighted. If we change the extension of the file to .ts, Visual Studio Code immediately underlines bits of the code that need our attention in red:
Most of the errors are TypeScript asking for some type information. So, let's add some types to our code:
interface IProduct {
name: string;
unitPrice: number;
}
function calculateTotalPrice(product: IProduct, quantity: number, discount: number): number {
var priceWithoutDiscount: number = product.price * quantity;
var discountAmount: number = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
Don't worry if you don't understand what we just added; we'll go through types in the next section. The key point is that we now have a single error highlighted to us, which is, in fact, the bug:
The bug is that our function references a price property in the product object that doesn't exist. The property that we should reference is unitPrice.
- UNIX編程藝術
- Java程序設計實戰教程
- C語言程序設計
- Scientific Computing with Scala
- R Data Analysis Cookbook(Second Edition)
- Android Wear Projects
- RESTful Java Web Services(Second Edition)
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- 高效使用Greenplum:入門、進階與數據中臺
- 絕密原型檔案:看看專業產品經理的原型是什么樣
- 菜鳥成長之路
- Practical Time Series Analysis
- Implementing DevOps with Ansible 2
- Swift編程實戰:iOS應用開發實例及完整解決方案
- Web前端開發全程實戰:HTML5+CSS3+JavaScript+jQuery+Bootstrap