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

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.

主站蜘蛛池模板: 阿拉善左旗| 武汉市| 永兴县| 项城市| 正镶白旗| 黄平县| 房山区| 连城县| 永胜县| 林口县| 兴宁市| 崇左市| 商城县| 衡阳县| 黄冈市| 思南县| 长治县| 容城县| 焉耆| 响水县| 盐亭县| 古蔺县| 成武县| 同江市| 阳朔县| 巴彦县| 金平| 商都县| 昌平区| 平度市| 克拉玛依市| 仲巴县| 乌拉特中旗| 茂名市| 中宁县| 平湖市| 菏泽市| 元阳县| 汾西县| 石首市| 浏阳市|