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

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.

主站蜘蛛池模板: 东港市| 张家港市| 保定市| 中方县| 黄石市| 东阿县| 洪泽县| 布尔津县| 喀什市| 昆明市| 南澳县| 吉木乃县| 东明县| 额尔古纳市| 特克斯县| 绵阳市| 临漳县| 织金县| 灵丘县| 永顺县| 武隆县| 孟村| 安溪县| 册亨县| 乌兰县| 海伦市| 吐鲁番市| 诸城市| 天等县| 台南县| 克什克腾旗| 卫辉市| 凤冈县| 巴南区| 宜宾县| 武穴市| 巴青县| 越西县| 泸州市| 大竹县| 呈贡县|