- Learn React with TypeScript 3
- Carl Rippon
- 130字
- 2021-06-10 19:16:34
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.
- Let's give this a try on our Product interface by making the name property readonly:
interface Product {
readonly name: string;
unitPrice: number;
}
- Let's also make sure we have an instance of the Product interface in place:
const table: Product = {
name: "Table",
unitPrice: 500
};
- 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.
推薦閱讀
- 手機安全和可信應用開發指南:TrustZone與OP-TEE技術詳解
- C++面向對象程序設計(第三版)
- PWA入門與實踐
- 小創客玩轉圖形化編程
- 微服務與事件驅動架構
- BeagleBone Media Center
- Lua程序設計(第4版)
- JavaScript+Vue+React全程實例
- Building an RPG with Unity 2018
- Learning JavaScript Data Structures and Algorithms
- Python之光:Python編程入門與實戰
- ABAQUS6.14中文版有限元分析與實例詳解
- Clojure編程樂趣
- Java Web應用開發
- Instant AppFog