一、readonly修饰符
只读修饰符:修饰的目标是只读的,不在编译结果中。
1.接口或者类型别名中使用 readonly 修饰符
2.数组中使用 readonly 修饰符
这里 readonly 修饰的是 数组类型 ,涉及到改变数组的函数都不能再使用,索引也是只读的,因此利用改变数组索引的方式来修改数组也不可行。
通过重新赋值的方式, arr1 数组中的值依旧可以改变。
下面是在接口 Users 中为数组 arr 添加只读修饰符,此时接口中的属性 arr 是只读的,不可通过直接赋值更改,但是可以改变数组里的内容。
interface Users {
readonly ids: string,
name: string,
age: number,
readonly arr: string[]
}
let users: Users = {
ids: '1',
name: 'kevin',
age: 18,
arr: ["a","b","c"]
}
users.arr.push('d')
console.log(users); // { ids: '1', name: 'kevin', age: 18, arr: [ 'a', 'b', 'c', 'd' ] }
如果既希望对象中的数组属性本身不能被重新赋值,也希望数组不能被更改可以这样来书写:
interface Users {
readonly ids: string,
name: string,
age: number,
readonly arr: readonly string[]
}