LoginSignup
1
0

【TypeScript】オブジェクトのすべてのプロパティをreadonlyにする

Last updated at Posted at 2024-03-28

Readonly<T>を使用するとオブジェクトのすべてのプロパティをreadonlyにできます。

type User = {
  id: number,
  name: string,
}
 
const user: Readonly<User> = {
  id: 1,
  name: '田中',
};
 
user.name = '佐藤'
// Cannot assign to 'title' because it is a read-only property.

Readonly<T>は再帰的にreadonlyにしません。上記の例でnameがオブジェクト型でもnameが持つプロパティはreadonlyになりません。

1
0
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
1
0