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

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.

主站蜘蛛池模板: 蓬安县| 灵川县| 太康县| 多伦县| 弋阳县| 天等县| 庆城县| 徐水县| 女性| 交口县| 西丰县| 绥芬河市| 贵港市| 营山县| 望谟县| 丰宁| 鞍山市| 嫩江县| 溆浦县| 栾川县| 沙洋县| 蕉岭县| 出国| 诸暨市| 九龙城区| 定南县| 全南县| 绥中县| 疏勒县| 马关县| 张掖市| 东丽区| 甘孜县| 交口县| 茌平县| 剑川县| 凤城市| 岱山县| 广水市| 红安县| 普定县|