LoginSignup
2
3

More than 3 years have passed since last update.

TypeScriptのReadonly型の挙動

Posted at

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' }
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3