LoginSignup
1
1

More than 3 years have passed since last update.

typescript コンストラクタ

Posted at

typescriptでは、コンストラクタの宣言の仕方をシンプルに書くことができる仕組みが備わっています。
constructor()の引数にpublic 変数名:型を宣言することで、クラスのメンバとして使うことができます。

冗長なコンストラクタの宣言方法
class Vihicle {
  color: string
  constructor(color: string) {
    this.color = color
  }
}

const vihicle = new Vihicle('red')
console.log(vihicle.color) // => red
シンプルなコンストラクタの宣言方法
class Vihicle {
  constructor(public color: string) {}
}

const vihicle = new Vihicle('red')
console.log(vihicle.color) // => red

クラスを継承する場合

class Vihicle {
  constructor(public color: string) {}
}

class Car extends Vihicle {
  constructor(public year: number, color:string) {
    super(color)
  }
}

const car = new Car(1995, 'red')
console.log(car.year) // => 1995
console.log(car.color) // => red

コンストラクタが実装されたクラスを継承する場合は、サブクラスのコンストラクタでsuper()を実行する必要があります。
superメソッドに引数を指定することでスーパークラスのコンストラクタに値を渡すことができます。

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