- 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.
推薦閱讀
- JavaFX Essentials
- Python計(jì)算機(jī)視覺編程
- Learning SciPy for Numerical and Scientific Computing(Second Edition)
- 西門子S7-200 SMART PLC編程從入門到實(shí)踐
- Python全棧數(shù)據(jù)工程師養(yǎng)成攻略(視頻講解版)
- Getting Started with Python and Raspberry Pi
- Go語(yǔ)言編程
- Clean Code in C#
- 自學(xué)Python:編程基礎(chǔ)、科學(xué)計(jì)算及數(shù)據(jù)分析(第2版)
- Mastering Android Studio 3
- PHP Microservices
- Managing Windows Servers with Chef
- Web前端開發(fā)精品課:HTML5 Canvas開發(fā)詳解
- 新手學(xué)ASP.NET 3.5網(wǎng)絡(luò)開發(fā)
- Python自動(dòng)化運(yùn)維:技術(shù)與最佳實(shí)踐