File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -98,6 +98,49 @@ function createSquare(config: SquareConfig): { color: string; area: number } {
9898let mySquare = createSquare ({color: " black" });
9999```
100100
101+ # 只读属性
102+
103+ 一些对象属性只能在对象刚刚创建的时候修改其值。
104+ 你可以在属性名前用` readonly ` 来指定只读属性:
105+
106+ ``` ts
107+ interface Point {
108+ readonly x: number ;
109+ readonly y: number ;
110+ }
111+ ```
112+
113+ 你可以通过赋值一个对象字面量来构造一个` Point ` 。
114+ 赋值后,` x ` 和` y ` 再也不能被改变了。
115+
116+ ``` ts
117+ let p1: Point = { x: 10 , y: 20 };
118+ p1 .x = 5 ; // error!
119+ ```
120+
121+ TypeScript具有` ReadonlyArray<T> ` 类型,它与` Array<T> ` 相似,只是把怕有可变方法去掉了,因此可以确保数组创建后再也不能被修改:
122+
123+ ``` ts
124+ let a: number [] = [1 , 2 , 3 , 4 ];
125+ let ro: ReadonlyArray <number > = a ;
126+ ro [0 ] = 12 ; // error!
127+ ro .push (5 ); // error!
128+ ro .length = 100 ; // error!
129+ a = ro ; // error!
130+ ```
131+
132+ 上面代码的最后一行,可以看到就算把整个` ReadonlyArray ` 赋值到一个普通数组也是不可以的。
133+ 但是你可以用类型断言重写:
134+
135+ ``` ts
136+ a = ro as number [];
137+ ```
138+
139+ ## ` readonly ` vs ` const `
140+
141+ 最简单判断该用` readonly ` 还是` const ` 的方法是看要把它做为变量使用还是做为一个属性。
142+ 做为变量使用的话用` const ` ,若做为属性则使用` readonly ` 。
143+
101144# 额外的属性检查
102145
103146我们在第一个例子里使用了接口,TypeScript让我们传入` { size: number; label: string; } ` 到仅期望得到` { label: string; } ` 的函数里。
@@ -282,6 +325,18 @@ interface NumberDictionary {
282325}
283326```
284327
328+ 最后,你可以将索引签名设置为只读,这样就防止了给索引赋值:
329+
330+ ``` ts
331+ interface ReadonlyStringArray {
332+ readonly [index : number ]: string ;
333+ }
334+ let myArray: ReadonlyStringArray = [" Alice" , " Bob" ];
335+ myArray [2 ] = " Mallory" ; // error!
336+ ```
337+
338+ 你不能设置` myArray[2] ` ,因为索引签名是只读的。
339+
285340# 类类型
286341
287342## 实现接口
Original file line number Diff line number Diff line change @@ -417,6 +417,8 @@ kitty.numLives--;
417417```
418418
419419除非你使用特殊的方法去避免,实际上` const ` 变量的内部状态是可修改的。
420+ 幸运的是,TypeScript允许你将对象的成员设置成只读的。
421+ [ 接口] ( ./Interfaces.md ) 一章有详细说明。
420422
421423# ` let ` vs. ` const `
422424
@@ -431,6 +433,8 @@ kitty.numLives--;
431433这个手册大部分地方都使用了` let ` 。
432434
433435跟据你的自己判断,如果合适的话,与团队成员商议一下。
436+ Fortunately, TypeScript allows you to specify that members of an object are ` readonly ` .
437+ The [ chapter on Interfaces] ( ./Interfaces.md ) has the details.
434438
435439# 解构
436440
You can’t perform that action at this time.
0 commit comments