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

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.

主站蜘蛛池模板: 班玛县| 岳阳县| 海伦市| 随州市| 凌云县| 南川市| 桃源县| 尤溪县| 墨玉县| 太白县| 金溪县| 峨边| 繁峙县| 仁怀市| 巨野县| 营山县| 横峰县| 文安县| 贺州市| 汽车| 江孜县| 北海市| 乌鲁木齐市| 沧源| 麻江县| 社旗县| 富川| 新泰市| 德阳市| 贵州省| 佛坪县| 乌海市| 长沙市| 涪陵区| 德令哈市| 汤原县| 新邵县| 九寨沟县| 友谊县| 金乡县| 莱阳市|