|
@ -0,0 +1,27 @@ |
|
|
|
|
|
// 只读修饰符:readonly,表示使用 readonly 关键字修饰属性是只读的,只能修饰属性不能修饰方法
|
|
|
|
|
|
|
|
|
|
|
|
class Person { |
|
|
|
|
|
// 只读属性
|
|
|
|
|
|
// 注意:只要是 readonly 来修饰的属性,必须手动提供明确的类型,否侧会变成字面量类型
|
|
|
|
|
|
// readonly age = 18 age 的类型为 18,字面量类型
|
|
|
|
|
|
readonly age: number = 18 |
|
|
|
|
|
|
|
|
|
|
|
constructor(age: number) { |
|
|
|
|
|
this.age = age |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
setAge() { |
|
|
|
|
|
// age 是只读属性,不能更改
|
|
|
|
|
|
// this.age = 20
|
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// 在接口中使用 readonly
|
|
|
|
|
|
interface Person { |
|
|
|
|
|
readonly name: string |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// readonly 的作用是一样的,表示当前属性是只读的
|
|
|
|
|
|
let obj: { readonly name: string } = { |
|
|
|
|
|
name: 'jack' |
|
|
|
|
|
} |