- 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.
- AngularJS入門與進階
- C# 7 and .NET Core Cookbook
- SQL Server 2016從入門到精通(視頻教學(xué)超值版)
- 跟“龍哥”學(xué)C語言編程
- 用Flutter極速構(gòu)建原生應(yīng)用
- SharePoint Development with the SharePoint Framework
- Unreal Engine 4 Shaders and Effects Cookbook
- Flowable流程引擎實戰(zhàn)
- 后臺開發(fā):核心技術(shù)與應(yīng)用實踐
- Django 5企業(yè)級Web應(yīng)用開發(fā)實戰(zhàn)(視頻教學(xué)版)
- jQuery for Designers Beginner's Guide Second Edition
- scikit-learn Cookbook(Second Edition)
- 軟件工程與UML案例解析(第三版)
- 高效使用Greenplum:入門、進階與數(shù)據(jù)中臺
- INSTANT Premium Drupal Themes