0
1

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チートシート2(クラス)

Last updated at Posted at 2021-12-28

1:クラス

class Person {
    name: string;
    constructor(initName: string) {
        this.name = initName;
    }
}

const suda = new Person("masaki");

2:this

メソッドはアロー関数で書かない方がいい
class Person {
  name: string;
  constructor(initName: string) {
    this.name = initName;
  }

  greeting(this: { name: string }) {
    console.log(`hello,${this.name}`);
  }
}

3:クラスを型としてつかう

クラスを定義するのはオブジェクトの型も同時に定義している
class Person {
  private name: string;
  private age: number;
  constructor(initName: string, initAge: number) {
    this.name = initName;
    this.age = initAge;
  }
  incrementAge() {
    this.age += 1;
  }
  greeting(this: Person) {
    console.log(`hello,${this.name},${this.age}yearsOld`);
  }

//↑↓は同じ意味 クラスを型として使えば、プロパティが増えても書き直す必要ない

  // greeting(this: { name: string; age: string }) {
  //   console.log(`hello,${this.name},${this.age}yearsOld`);
  // }
}

let person:Person

const suda = new Person("masaki");

4:private,public

・private そのクラスでのみアクセス可能 ・protected そのクラスとサブクラスでのみアクセス可能 ・public どこからでもアクセス可能(デフォルト)
class Person {
  public name: string;
  private age: number;
  constructor(initName: string, initAge: number) {
    this.name = initName;
    this.age = initAge;
  }
  incrementAge() {
    this.age += 1;
  }
  greeting(this: Person) {
    console.log(`hello,${this.name}`);
  }
}

5:readonly

クラスの中でも外でも読むだけ
class Person {
  readonly name: string;
  readonly age: number;
  constructor(initName: string, initAge: number) {
    this.name = initName;
    this.age = initAge;
  }
//   incrementAge() {
//     this.age += 1;
//   }
  greeting(this: Person) {
    console.log(`hello,${this.name}`);
  }
}

6:extends

constructorの引数を増やしたかったらsuper()を使う
class Teacher extends Person {
  constructor(name: string, age: number, public subject: string) {
    super(name, age);
  }
}

const teacher = new Teacher("masaki", 28, "English");

7:getter,setter

・getter データを取得した時に処理を実行 ・setter 変更した時に処理を実行

関数名は同じにできる

class Teacher extends Person {
  get subject() {
    if (!this._subject) {
      throw new Error("no subject");
    }

    return this._subject;
  }

  set subject(value) {
    this._subject = value;
  }
  constructor(name: string, age: number, public _subject: string) {
    super(name, age);
  }
}

const teacher = new Teacher("masaki", 28, "English");
//getter
teacher.subject
//setter
teacher.subject = 'Math'

8:abstract

abstractがついたクラスはインスタンス化できない サブクラスを作るためのクラス
abstract class AbstractClass {
  protected constructor(private name: string, protected old: number) {
  }

  showInfo(): void {
      console.log(`name: ${this.name}, ${this.showDetail()}`);
  }

  //このクラスを継承したクラスはshowDetailメソッドを持つ必要がある
  //戻り値の型もしっかり定義
  protected abstract showDetail(): string;
}

class ExtendedClass extends AbstractClass {
  constructor(name: string, old: number, private weight: number) {
      super(name, old);
  }

  showDetail(): string {
      return `old: ${this.old}, weight: ${this.weight}`;
  }
}

const extendedClass = new ExtendedClass('ジョン', 3, 20);
extendedClass.showInfo(); // name: ジョン, old: 3, weight: 20

9:シングルトンパターン

クラスからインスタンスを1つしか作れなくする

1:コンストラクターにprivateをつけ外部からアクセスできないように(インスタンス化できない)する
2:staticメソッドを作成
3:staticプロパティを作成
4:staticメソッドの中でインスタンス化をし、staticプロパティに代入
5:staticメソッドの中ですでにインスタンス化されていたらそれをそのまま返す


class Teacher extends Person {
  private static instance: Teacher;
  explainJob() {
    console.log(`I am a teacher and I teach ${this.subject}.`);
  }
  get subject(): string {
    if (!this._subject) {
      throw new Error('There is no subject.');
    }
    return this._subject;
  }
  set subject(value) {
    if (!value) {
      throw new Error('There is no subject.');
    }
    this._subject = value;
  }
  private constructor(name: string, age: number, private _subject: string) {
    super(name, age);
  }
  static getInstance() {
    if (Teacher.instance) return Teacher.instance;
    Teacher.instance = new Teacher('Quill', 38, 'Math');
    return Teacher.instance;
  }
}
const teacher = Teacher.getInstance();
const teacher2 = Teacher.getInstance();
console.log(teacher, teacher2);
//同じものが返る
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?