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

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.

主站蜘蛛池模板: 南城县| 榆中县| 中阳县| 阿尔山市| 定兴县| 芒康县| 汕头市| 伊金霍洛旗| 怀远县| 南岸区| 黑山县| 小金县| 缙云县| 旬阳县| 化德县| 保山市| 青田县| 南陵县| 呼和浩特市| 绥江县| 敦化市| 林州市| 黄石市| 安化县| 温宿县| 盐池县| 昌平区| 关岭| 锡林郭勒盟| 余江县| 德安县| 额济纳旗| 乃东县| 赣州市| 长垣县| 浦江县| 扎鲁特旗| 云林县| 湾仔区| 绥宁县| 平顺县|