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

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.

主站蜘蛛池模板: 太白县| 临沭县| 垫江县| 肃南| 汉沽区| 平罗县| 湘阴县| 镇雄县| 廉江市| 洛宁县| 海兴县| 镇巴县| 崇阳县| 鄂托克旗| 布拖县| 永年县| 商丘市| 朝阳县| 沾化县| 石阡县| 澎湖县| 大洼县| 宽甸| 南安市| 华池县| 莱西市| 永宁县| 皮山县| 瓦房店市| 通榆县| 河曲县| 乐陵市| 揭阳市| 建德市| 秭归县| 临潭县| 霍林郭勒市| 中江县| 宜阳县| 大兴区| 西林县|