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

Objects

The object type is shared with JavaScript and represents a non-primitive type. Objects can contain typed properties to hold bits of information.

Let's work through an example:

  1. Let's enter the following code into the TypeScript playground, which creates an object with several properties of information:
const customer = {
name: "Lamps Ltd",
turnover: 2000134,
active: true
};

If we hover over name, turnover, and active, we'll see that TypeScript has smartly inferred the types to be string, number, and boolean respectively.

  1. If we hover over the customer variable name, we see something interesting:

  1. Rather than the type being object, it is a specific type with name, turnover, and active properties. On the next line, let's set the turnover property to some other value:
customer.turnover = 500000;

As we type the turnover property, IntelliSense provides the properties that are available on the object:

We used const to declare the customer variable and then was able to change one of its property values later in the program. Shouldn't this have thrown an error? Well, the customer variable reference hasn't changed — just some properties within it. So, this is fine with the TypeScript compiler.
  1. This line of code is perfectly fine, so we don't get any complaints from the compiler. If we set the turnover to a value that has an incorrect type, we'll be warned as we would expect:

  1. Now let's set a property on customer that doesn't exist yet:
customer.profit = 10000;

We'll see that TypeScript complains:

This makes sense if we think about it. We've declared customer with name, turnover, and active properties, so setting a profit property should cause an error. If we wanted a profit property, we should have declared it in the original declaration.

In summary, the object type is flexible because we get to define any properties we require, but TypeScript will narrow down the type to prevent us incorrectly typing a property name.

主站蜘蛛池模板: 和龙市| 嘉义县| 务川| 英吉沙县| 宜黄县| 新源县| 漳州市| 思茅市| 南昌市| 昭通市| 万盛区| 安国市| 舟山市| 临沧市| 乃东县| 隆昌县| 申扎县| 西畴县| 昌江| 东乌珠穆沁旗| 儋州市| 宜君县| 张掖市| 泸水县| 永城市| 淮北市| 新巴尔虎右旗| 云阳县| 星子县| 平湖市| 突泉县| 曲周县| 张北县| 永仁县| 溧水县| 塔城市| 南宁市| 宝清县| 舟山市| 陕西省| 安国市|