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

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.

主站蜘蛛池模板: 玉门市| 潼南县| 石楼县| 富阳市| 视频| 白银市| 梨树县| 上栗县| 白山市| 宁远县| 汤原县| 福贡县| 沂源县| 江陵县| 珲春市| 工布江达县| 喀什市| 洞口县| 调兵山市| 绵阳市| 乌兰察布市| 万全县| 罗平县| 尉氏县| 安西县| 阿瓦提县| 宁阳县| 五寨县| 扶绥县| 晋州市| 长岭县| 积石山| 闽侯县| 尖扎县| 马边| 吴桥县| 铁岭县| 泗水县| 太和县| 犍为县| 澄江县|