Readonlyにするいろんな方法
① readonlyプロパティ (特定プロパティのみreadonlyにする
type State = {
// 読み込み専用
readonly id: number
name: string
}
const state:State = {
id: 22,
name: 'success'
}
state.name = 'bbb' // OK
state.id = 11 // コンパイルエラー
② Readonly型 (全プロパティreadonly)
type User = {
id: number,
name: string
}
// 全プロパティがreadonlyになる
const user: Readonly<User> = {
id: 34,
name: 'Yorinton'
}
user.id = 22 // コンパイルエラー
user.name = 'kentaro' // コンパイルエラー
③ Object.freeze
type Person = {
id: number
name: string
}
let person: Person = {
id: 99,
name: 'BigMam'
}
// person2はReadonly型になる
let person2 = Object.freeze(person)
person2.id = 22 // コンパイルエラー
person2.name = 'bbb' // コンパイルエラー
// personの方を書き換えてみる
person.id = 22 // コンパイルOK
person.name = 'bbb' // コンパイルOK
// コンパイルは通るが、personのプロパティの値は書き換わらない
console.log(person) // { id: 99, name: 'BigMam' }
console.log(person2) // { id: 99, name: 'BigMam' }