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

Extending interfaces

Interfaces can extend other interfaces so that they inherit all the properties and methods from its parent. We do this using the extends keyword after the new interface name and before the interface name that is being extended.

Let's look at the following example:

  1. We create a new interface, taking Product as a base, and add information about discount codes:
interface Product {
name: string;
unitPrice: number;
}

interface DiscountCode {
code: string;
percentage: number;
}

interface ProductWithDiscountCodes extends Product {
discountCodes: DiscountCode[];
}
  1. We can create an instance of the interface in the usual way, filling in properties from the base interface as well as the child interface:
const table: ProductWithDiscountCodes = {
name: "Table",
unitPrice: 500,
discountCodes: [
{ code: "SUMMER10", percentage: 0.1 },
{ code: "BFRI", percentage: 0.2 }
]
};

Interfaces allow us to create complex but flexible structured types for our TypeScript program to use. They are a really important feature that we can use to create a robust, strongly-typed TypeScript program.

主站蜘蛛池模板: 望江县| 米易县| 崇明县| 潞西市| 绵竹市| 惠安县| 龙海市| 崇信县| 永川市| 荆州市| 正镶白旗| 和田县| 衡阳县| 海门市| 吉木乃县| 闽侯县| 朝阳区| 渑池县| 麦盖提县| 长宁县| 信宜市| 黑山县| 丽江市| 农安县| 安阳县| 冕宁县| 定襄县| 峡江县| 会东县| 库尔勒市| 绥江县| 拜城县| 庄河市| 南通市| 娱乐| 潞城市| 岱山县| 南昌县| 汝城县| 烟台市| 松溪县|