- 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.
推薦閱讀
- Java多線程編程實戰指南:設計模式篇(第2版)
- Flask Blueprints
- Visual FoxPro程序設計教程
- NativeScript for Angular Mobile Development
- INSTANT Weka How-to
- 編寫高質量代碼:改善C程序代碼的125個建議
- D3.js 4.x Data Visualization(Third Edition)
- Clojure for Machine Learning
- App Inventor少兒趣味編程動手做
- Magento 2 Beginners Guide
- C#面向對象程序設計(第2版)
- jQuery從入門到精通(微課精編版)
- Parallel Programming with Python
- Internet of Things with Arduino Cookbook
- Learning Azure DocumentDB