Objectの構造を定義するもの
type alias, interface, class ってやつがある。
Interface編
Type Alias編
という事で今回は Class編
Class
色んな言語で採用されている手法。 Class は Interface や Type Alias よりも多くの機能がある。
定義や使用方法
定義としてはこんな感じ
class Item {
name: string;
unitPrice: number;
}
使用時は new
というキーワードを使用してインスタンスを生成して使う
const pen = new Item();
pen.name = "ペン";
pen.unitPrice = 100;
コンストラクタというインスタンスの初期化を行う関数を定義して、それを利用してインスタンスの初期化を行う事もできる。
class Item {
name: string;
unitPrice: number;
constructor(name: string, unitPrice: number) {
this.name = name;
this.unitPrice = unitPrice;
}
}
const pen = new Pen("ペン",100);
また以下のように Constructor のパラメータの前にpublic
キーワードを設定する事で、プロパティを実装する事もできる
class Item {
constructor(public name: string, public unitPrice: number) {
this.name = name;
this.unitPrice = unitPrice;
}
}
const pen = new Pen("ペン",100);
classの機能
methodの実装
TypeやInterfaceでは出来ないが、Classにはできる事の一つとしてメソッドの実装を定義することができる点 ( totalPrice を わざわざ const で宣言する必要無いって話はおいておくとしてw
class SaleRow {
item: Item;
count: number;
getTotalPrice(): number {
const totalPrice = this.item.unitPrice * this.count;
return totalPrice;
}
}
InterfaceのImprement
Interface と Class を併用したりもできます。
interface SaleRowInterface {
item: Item;
count: number;
getTotalPrice(): number;
}
class SaleRow imprements SaleRowInterface {
item: Item;
count: number;
getTotalPrice(): number {
const totalPrice = this.item.unitPrice * this.count;
return totalPrice;
}
}
classの拡張
class Item {
name: string;
unitPrice: number;
}
class HaveTaggedItem extends Item {
tags: string[];
}
抽象クラス(Abstract Class)
継承のみ可能でインスタンス化出来ないClass
abstract class Item {
name: string;
unitPrice: number;
}
expirationDate(賞味期限)プロパティを持つ食品専用のclassを定義する事とかができる.
class FoodItem extends Item {
constructor(public expirationDate: Date) {
this.expirationDate = Date;
}
}
メソッドに abstract をつける事で、 小ClassではcalcInTaxを実装する必要がある(軽減税率とかつらいですよね
abstract class Item {
name: string;
unitPrice: number;
abstract calcInTax();
}
アクセス修飾子
private
や public
などのアクセス修飾子をつける事でアクセスの権限を調整できる
class Item {
name: string;
unitPrice: number;
private tax: number;
}
getter / setter プロパティ
getter や setterが定義できる.
class Item {
name: string;
private _unitPrice: number;
get unitPrice(): number {
return this._unitPrice || 0;
}
set unitPrice(value: number) {
if (value < 0) {
value = 0;
}
this._unitPrice = value;
}
}
Staticとかあるけど、他の言語と同じようなイメージで理解できるので、一旦おいておく。