只读修饰符不在编译的结果中。
// 修饰普通成员interface A {readonly a: number}let aa: A = {a: 1}aa.a = 2 // 这里 ts 会提示错误,因为 a 被设置了只读修饰符,所以 a 的值只可以被赋值一次,不可以更改重新赋值// 修饰数组对象成员interface B {readonly b: number[]readonly c: readonly number[] // 如果不喜欢数组被重新赋值和修改可以这样写}let bb: B = {b: [1, 2, 3],c: [1, 2, 3]}bb.b = [1, 2, 3, 4] // 这里 ts 会提示错误,因为 a 被设置了只读修饰符,所以 a 的值只可以被赋值一次,不可以更改重新赋值bb.b.push(4) // 不能重新赋值但是可以对数组进行添加或移除// 直接修饰一个数组// 使用 let 声明,数组可以重新赋值但不可更改数组成员let arr1: readonly number[] = [1, 2, 3]// 使用 const 声明,数组不可以重新赋值也不可更改数组成员const arr2: readonly number[] = [1, 2, 3]
