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

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.

主站蜘蛛池模板: 乐平市| 聂荣县| 西昌市| 宕昌县| 绥宁县| 湖州市| 皋兰县| 龙江县| 长沙县| 土默特左旗| 吴忠市| 徐汇区| 富宁县| 攀枝花市| 洛浦县| 洱源县| 姚安县| 腾冲县| 开远市| 吉木萨尔县| 磴口县| 张北县| 福州市| 海宁市| 锡林浩特市| 正镶白旗| 濮阳市| 平阳县| 鹿邑县| 赣榆县| 耿马| 阿图什市| 晋宁县| 确山县| 游戏| 潼南县| 武夷山市| 体育| 达孜县| 甘南县| 高要市|