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

Readonly properties

We can stop a property from being changed after it has initially been set by using the readonly keyword before the property name.

  1. Let's give this a try on our Product interface by making the name property readonly:
interface Product {
readonly name: string;
unitPrice: number;
}
  1. Let's also make sure we have an instance of the Product interface in place:
const table: Product = {
name: "Table",
unitPrice: 500
};
  1. Let's change the name property table now on the next line:
table.name = "Better Table";

As expected, we get a compilation error:

readonly properties are a simple way of freezing their values after being initially set. A common use case is when you want to code in a functional way and prevent unexpected mutations to a property.

主站蜘蛛池模板: 新野县| 苗栗县| 舒城县| 巫溪县| 汪清县| 特克斯县| 吴堡县| 葵青区| 桐梓县| 崇阳县| 罗田县| 和政县| 定州市| 龙井市| 东乌珠穆沁旗| 烟台市| 黄龙县| 阿图什市| 木兰县| 汪清县| 韩城市| 白城市| 阿巴嘎旗| 靖边县| 衡山县| 泊头市| 义乌市| 绥滨县| 富裕县| 苏尼特右旗| 洞口县| 嵊泗县| 浦东新区| 皮山县| 阿勒泰市| 东至县| 洪湖市| 偏关县| 鹤庆县| 临夏县| 交城县|