- 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.
推薦閱讀
- 單片機C語言程序設計實訓100例:基于STC8051+Proteus仿真與實戰
- PyTorch自然語言處理入門與實戰
- 數據庫系統原理及MySQL應用教程
- PHP+MySQL網站開發技術項目式教程(第2版)
- 深入理解Java7:核心技術與最佳實踐
- Object-Oriented JavaScript(Second Edition)
- 用Flutter極速構建原生應用
- Learning ELK Stack
- Web Development with MongoDB and Node(Third Edition)
- Machine Learning in Java
- Arduino可穿戴設備開發
- R Data Science Essentials
- Android Sensor Programming By Example
- Drupal 8 Development:Beginner's Guide(Second Edition)
- Mastering Python