Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f9c13c7

Browse files
committed
feat: add 'readonly' modifier and fix write error
1 parent a66f991 commit f9c13c7

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

advanced/class.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ let a = new Animal('Jack');
265265
```ts
266266
class Animal {
267267
public name;
268-
private constructor (name) {
268+
protected constructor (name) {
269269
this.name = name;
270270
}
271271
}
@@ -291,6 +291,36 @@ class Animal {
291291
}
292292
```
293293

294+
### readonly
295+
296+
只读属性关键字,只允许出现在属性声明或索引签名中。
297+
298+
```ts
299+
class Animal {
300+
readonly name;
301+
public constructor(name) {
302+
this.name = name;
303+
}
304+
}
305+
306+
let a = new Animal('Jack');
307+
console.log(a.name); // Jack
308+
a.name = 'Tom';
309+
310+
// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.
311+
```
312+
313+
注意如果 `readonly` 和其他访问修饰符同时存在的话,需要写在其后面。
314+
315+
```ts
316+
class Animal {
317+
// public readonly name;
318+
public constructor(public readonly name) {
319+
this.name = name;
320+
}
321+
}
322+
```
323+
294324
### 抽象类
295325

296326
`abstract` 用于定义抽象类和其中的抽象方法。

0 commit comments

Comments
 (0)