1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScriptのクラスについて

Last updated at Posted at 2024-02-19

事前知識

オブジェクト

コード上で扱うもの。変数、定数、メソッドなどあらゆるものを含み得る。

const personData: {
    name: string;
    age: number;
    hobbies: string[];
    addHobby: (hobby: string) => void;
}  = {
    name: 'John',
    age: 30,
    hobby: ['sports', 'reading', 'travel'],
    addHobby: function (hobby: string) {
        this.hobbies.push(hobby);
    }
};

クラスとインスタンス

クラス

オブジェクトの設計図。

コンストラクタ

クラスを基に宣言されたインスタンスに紐づくメソッド。
インスタンスの宣言時に実行される。

// どんなプロパティ・メソッドを持つのかを記述する
class Person {
    name: string;
    age: number;
    // 初期値を宣言することも可
    hobbies: string[] = []:

    // オブジェクトの宣言時に実行されるメソッド
    constructor(name: string, age: number) {
        // プロパティの初期化
        this.name = name;
        this.age = age;
    }

    addHobby(hobby: string) {
        this.hobbies.push(hobby);
    }
};

インスタンス

クラスの定義に基づいて作成されたオブジェクト。

// newでオブジェクトを宣言する
const personData = new Person('John', 30);
personData.addHobby('sports');

privateとpublic

privateはプロパティへのアクセスを制限するための修飾子。
クラス内でのみアクセスが可能な状態にする。

publicはアクセスを制限しない。
初期値はこちらのため、publicにしたい場合は付与不要。

class Person {
    // 頭にprivateを付ける
    private hobbies: string[] = []:
    ...
    addHobby(hobby: string) {
        this.hobbies.push(hobby);
    }
};
// Person外から値を追加しようとすると、エラーになる
personData.hobbies[0] = 'sports';
// Person内で定義されている関数からアクセスすると、正常に実行される
personData.addHobby('sports');
    
};

プロパティ初期化のショートカット構文

class宣言時に設定するプロパティは、初期値を設定するか初期化を行う必要がある。

class Person {
    private name: string;
    age: number;
    hobbies: string[] = []: // 初期値を宣言

    // オブジェクトの宣言時に実行されるメソッド
    constructor(n: string, a: number) {
        this.name = n; // nameの初期化
        this.age = a; // ageの初期化
    }
};

これについて、constructorの引数にアクセス修飾子を追記することで二重の定義を回避できる。
この方法を取る場合、渡す引数の変数名がそのままプロパティの名前になる。
アクセス修飾子を明示しなければならない。

class Person {
    // 最初のパラメータの宣言を削除

    // public, privateどちらの場合でも明示的に記述する
    constructor(
        private name: string,
        public age: number,
        private hobbies: string[]
    ) {
        // パラメータの初期化用の記述も削除
    }
};

readonly

初期化後に変更したくないものに付与するアクセス修飾子。

// Objectの設計図、どんな値・メソッドを持つのかを記述する。
class Person {
    constructor(
        private readonly id :number, // idは初期設定後変更したくないため付与
        private name: string,
        public age: number,
        private hobbies: string[]
    ) {
    
    }
};

const personData = new Person(01, 'John', 30); // 01は後から変更できない

次の記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?