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

Type aliases

In simple terms, a type alias creates a new name for a type. To define a type alias, we use the type keyword, followed by the alias name, followed by the type that we want to alias.

We'll explore this with the following example:

  1. Let's create a type alias for the getTotal method in the OrderDetail interface we have been working with. Let's try this in the TypeScript playground:
type GetTotal = (discount: number) => number;

interface OrderDetail {
product: Product;
quantity: number;
getTotal: GetTotal;
}

Nothing changes with objects that implement this interface – it is purely a way we can structure our code. It arguably makes the code a little more readable.

  1. Type aliases can also define the shape of an object. We could use a type alias for our Product and OrderDetail types that we previously defined with an interface:
type Product = {
name: string;
unitPrice: number;
};

type OrderDetail = {
product: Product;
quantity: number;
getTotal: (discount: number) => number;
};
  1. We use these types in exactly the same way as we used our interface-based types:
const table: Product = {
name: "Table",
unitPrice: 500
};

const orderDetail: OrderDetail = {
product: table,
quantity: 1,
getTotal(discount: number): number {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}
};

So, type aliases seem very similar to interfaces. What is the difference between a type alias and an interface? The main difference is that type aliases can't be extended or implemented from like you can with interfaces. So, for a simple structure that doesn't require inheritance, should we use an interface or should we use a type alias? There isn't strong reasoning to prefer either approach. However, we should be consistent with whichever approach we choose to improve the readability of our code.

主站蜘蛛池模板: 铜陵市| 呼伦贝尔市| 巨鹿县| 河津市| 漳州市| 石城县| 墨竹工卡县| 弥渡县| 广元市| 桂平市| 灵川县| 南丰县| 阿鲁科尔沁旗| 北安市| 海原县| 弥勒县| 高青县| 洞头县| 尼勒克县| 合川市| 和顺县| 开平市| 翼城县| 靖西县| 深水埗区| 阜宁县| 皋兰县| 孟州市| 内江市| 汉寿县| 略阳县| 潮安县| 凤凰县| 堆龙德庆县| 镇宁| 德化县| 乐昌市| 平武县| 德昌县| 乐山市| 郑州市|