- 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.
推薦閱讀
- Implementing Modern DevOps
- Learning Selenium Testing Tools with Python
- PHP 從入門到項(xiàng)目實(shí)踐(超值版)
- 跟“龍哥”學(xué)C語(yǔ)言編程
- 深入淺出Java虛擬機(jī):JVM原理與實(shí)戰(zhàn)
- UI智能化與前端智能化:工程技術(shù)、實(shí)現(xiàn)方法與編程思想
- SEO實(shí)戰(zhàn)密碼
- The Data Visualization Workshop
- Asynchronous Android Programming(Second Edition)
- Visual Basic程序設(shè)計(jì)實(shí)踐教程
- 時(shí)空數(shù)據(jù)建模及其應(yīng)用
- ExtJS Web應(yīng)用程序開發(fā)指南第2版
- Learning JavaScript Data Structures and Algorithms(Second Edition)
- Oracle實(shí)用教程
- 貫通Tomcat開發(fā)