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

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.

主站蜘蛛池模板: 始兴县| 新巴尔虎左旗| 铁岭县| 射阳县| 同仁县| 定日县| 庆城县| 陆河县| 古丈县| 新巴尔虎右旗| 基隆市| 筠连县| 虞城县| 怀安县| 布拖县| 凯里市| 万州区| 仙居县| 蕉岭县| 平安县| 镇江市| 崇州市| 新河县| 荆州市| 佳木斯市| 赤城县| 太仓市| 诸暨市| 舒城县| 浦县| 辉县市| 崇义县| 措勤县| 禄丰县| 北川| 桦甸市| 南宫市| 西乌珠穆沁旗| 石城县| 互助| 竹北市|