概要: このチュートリアルでは、TypeScriptクラスと、クラスを使用してオブジェクトを作成する方法について学習します。
TypeScriptクラスの紹介
JavaScriptには、JavaやC#などの他のプログラミング言語のようなクラスの概念がありません。ES5では、コンストラクタ関数とプロトタイプ継承を使用して「クラス」を作成できます。
たとえば、3つのプロパティssn、名、姓を持つPersonクラスを作成するには、次のコンストラクタ関数を使用します。
function Person(ssn, firstName, lastName) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
}Code language: TypeScript (typescript)次に、名と姓を連結して、次のように、その人のフルネームを取得するプロトタイプメソッドを定義できます
Person.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
}Code language: TypeScript (typescript)それから、新しいオブジェクトを作成することでPerson「クラス」を使用できます
let person = new Person('171-28-0926','John','Doe');
console.log(person.getFullName());Code language: TypeScript (typescript)コンソールには以下が出力されます
John DoeCode language: TypeScript (typescript)ES6を使用すると、クラスを定義できます。これは、コンストラクタ関数とプロトタイプ継承を作成するための単なる構文上の糖衣です
class Person {
ssn;
firstName;
lastName;
constructor(ssn, firstName, lastName) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
}
}Code language: TypeScript (typescript)クラス構文では、コンストラクタが明確に定義され、クラス内に配置されます。次に、getFullName()メソッドをクラスに追加します。
class Person {
ssn;
firstName;
lastName;
constructor(ssn, firstName, lastName) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}Code language: TypeScript (typescript)Personクラスを使用する方法は、Personコンストラクタ関数と同じです
let person = new Person('171-28-0926','John','Doe');
console.log(person.getFullName());Code language: TypeScript (typescript)TypeScriptクラスは、クラスのプロパティとメソッドに型注釈を追加します。次に、TypeScriptのPersonクラスを示します
class Person {
ssn: string;
firstName: string;
lastName: string;
constructor(ssn: string, firstName: string, lastName: string) {
this.ssn = ssn;
this.firstName = firstName;
this.lastName = lastName;
}
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}Code language: TypeScript (typescript)型をプロパティ、コンストラクタ、およびメソッドに注釈付けすると、TypeScriptコンパイラは対応する型のチェックを行います。
たとえば、ssnをnumberで初期化することはできません。次のコードはエラーになります
let person = new Person(171280926, 'John', 'Doe');Code language: TypeScript (typescript)概要
- TypeScriptでクラスを定義するには
classキーワードを使用します。 - TypeScriptはES6クラス構文を活用し、型注釈を追加してクラスをより堅牢なものにします。
このチュートリアルは役に立ちましたか?