LoginSignup
2
2

More than 3 years have passed since last update.

【TypeScript】Utility TypesのReadonlyを理解する

Last updated at Posted at 2021-03-12

この記事は何?

この記事は、Utility Typesの一つであるReadonlyについて理解する記事です。
Utility Typesってそもそも何?という型(方)は以下の記事を御覧ください🙇🏻
👉 TypeScriptのUtility Typesを理解して活用する

そもそも、TypeScriptって何?って型は以下を御覧ください
👉 JavaScriptを知っている方がTypeScriptをなんとなく理解するための記事① ~はじめに~

Readonly<Type>とは

TypeScript公式には以下のように書かれています。

Constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.
すべてのプロパティを読み取り専用に設定されたタイプを構築します。タイプのプロパティを再割り当てすることはできません。
https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

つまり、ある型をReadOnly(書き換え不可)にする型になります。

実際にコードの場合、以下のように表すことが出来ます。

type hogehoge = ReadOnly<>
// ふつーにHuman型を定義
interface Human {
    sex: 'woman' | 'man';
    old: number;
    height: number;
}

// tomオブジェクトを作成
const tom: Human = {
    sex: 'man',
    old: 14,
    height: 150
}

// tomの年齢は書き換え可能
tom.old = 15;

// Human型をReadOnlyにする
type StrictHuman = Readonly<Human>;

// トムの厳格な父のオブジェクトを作成
const tomStrictFather: StrictHuman = {
    sex: 'man',
    old: 34,
    height: 200
}

// ReadOnlyなので、書き換え不可
tomStrictFather.old = 35; // Cannot assign to 'old' because it is a read-only property.

このように、内容を変更したくないオブジェクトがある場合は、ReadOnly型を使うことで書き換え不可にすることができます。
値の変更により思わぬバグが起きる可能性もあるので、あらかじめReadOnlyで書き換え禁止にすることで、障害を防げるかもしれません!

おわりに

今回は、Utility TypesのReadonlyについて紹介しました。
是非、ご活用ください!

参考

2
2
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
2