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

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.

主站蜘蛛池模板: 汉中市| 全南县| 陇西县| 灯塔市| 德钦县| 简阳市| 乾安县| 龙门县| 朝阳市| 临沭县| 阿克苏市| 泰兴市| 绥宁县| 宝鸡市| 临桂县| 全州县| 东方市| 牡丹江市| 平邑县| 年辖:市辖区| 鹿邑县| 三门峡市| 河北省| 泌阳县| 长岛县| 大埔县| 望城县| 交城县| 乌拉特前旗| 南召县| 宁强县| 伊金霍洛旗| 邻水| 牟定县| 仙桃市| 乐陵市| 九龙城区| 汝南县| 涞水县| 蓝山县| 南木林县|