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

Properties

Properties are one of the elements that can be part of an interface. Properties can hold values associated with an object. So, when we define a property in an interface, we are saying that objects that implement the interface must have the property we have defined.

Let's start to play with an interface in the TypeScript playground:

  1. Enter the following interface:
interface Product {
name: string;
unitPrice: number;
}
  1. The preceding example creates a Product interface with name and unitPrice properties. Let's go on to use this interface by using it as the type for a table variable:
const table: Product = {
name: "Table",
unitPrice: 500
}
  1. Let's try to set a property that doesn't exist in the interface:
const chair: Product = {
productName: "Table",
price: 70
}

As expected, we get a type error:

  1. Properties on an interface can reference another interface because an interface is just a type. The following example shows an OrderDetail interface making use of a Product interface:
interface Product {
name: string;
unitPrice: number;
}

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

const table: Product = {
name: "Table",
unitPrice: 500
}

const tableOrder: OrderDetail = {
product: table,
quantity: 1
};

This gives us the flexibility to create complex object structures, which is critical when writing large, complex apps.

主站蜘蛛池模板: 当涂县| 筠连县| 体育| 太和县| 镇赉县| 永济市| 沐川县| 峨眉山市| 东乌珠穆沁旗| 揭西县| 霞浦县| 哈密市| 平湖市| 金川县| 长岭县| 潍坊市| 镇赉县| 综艺| 朔州市| 莆田市| 万安县| 双城市| 徐汇区| 滨海县| 青铜峡市| 墨竹工卡县| 棋牌| 兰溪市| 武乡县| 安图县| 黔东| 湘潭市| 永定县| 山西省| 修文县| 青田县| 台南县| 沅江市| 鄂尔多斯市| 马关县| 浦城县|