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

Configuring rules

The rules that tslint uses when checking our code are configurable in a file called tslint.json. In order to explore some of the rules, we first need a TypeScript file:

  1. So, let's create a file called orderDetail.ts with the following content in Visual Studio Code:
export interface Product {
name: string;
unitPrice: number;
}

export class OrderDetail {
product: Product;
quantity: number;
getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}
  1. Let's now create a tslint.json file. We define the rules we want to implement in a rules field. Let's add the following rule:
{
"rules": {
"member-access": true
}
}
  1. A full list of the rules can be found at: https://palantir.github.io/tslint/rules/. The member-access rule forces us to explicitly declare the access modifier for classes. We haven't explicitly defined the property and method access modifiers in the OrderDetail class because they are public by default. So, with our linting rule in place, Visual Studio Code will highlight the lack of access modifiers to us:

  1. As we put a public access modifier in front of the properties and method, the warnings go away:
export class OrderDetail {
public product: Product;
public quantity: number;
public getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
}

The member-access rule forces us to write more code – how can this be a good thing? The rule is useful if you're reading the code and don't know TypeScript well enough to understand that class members without access modifiers are public. So, it's great if our team consists of developers who don't know TypeScript that well yet, but not necessarily for an experienced team of TypeScript developers.

Lots of the tslint rules are like member-access – in some teams, they will work well and in others, they don't really add value. This is why rules are configurable!

主站蜘蛛池模板: 建水县| 张家港市| 乐平市| 怀化市| 靖安县| 松桃| 磐安县| 庄浪县| 建宁县| 林口县| 英山县| 太保市| 滁州市| 阳朔县| 青铜峡市| 穆棱市| 武清区| 乾安县| 阿鲁科尔沁旗| 邢台县| 翁牛特旗| 樟树市| 宝丰县| 洪江市| 章丘市| 龙江县| 安平县| 沙雅县| 乌鲁木齐市| 南投市| 渝北区| 金塔县| 天门市| 黄大仙区| 遵义县| 乌拉特前旗| 额尔古纳市| 察雅县| 兰西县| 自贡市| 新平|