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

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.

主站蜘蛛池模板: 吉隆县| 阳东县| 会理县| 上高县| 逊克县| 四子王旗| 宣化县| 阿拉尔市| 田阳县| 博爱县| 佳木斯市| 合作市| 潼南县| 缙云县| 吉木乃县| 安福县| 霍城县| 河南省| 屏东市| 阜新市| 普宁市| 元朗区| 泊头市| 策勒县| 平凉市| 义乌市| 遵义县| 绥中县| 黑河市| 五原县| 卓资县| 中西区| 靖州| 通化县| 东乌| 岚皋县| 略阳县| 红原县| 顺义区| 称多县| 大埔县|