TypeScript ジェネリッククラス

概要: このチュートリアルでは、TypeScript ジェネリッククラスの開発方法を学習します。

TypeScript ジェネリッククラス入門

ジェネリッククラスは、クラス名の後に続く山括弧 `<>` 内にジェネリック型パラメータリストを持っています。

class className<T>{
    //... 
}Code language: TypeScript (typescript)

TypeScript では、型パラメータリストに複数のジェネリック型を含めることができます。例えば

class className<K,T>{
    //...
}
Code language: TypeScript (typescript)

ジェネリック制約は、クラス内のジェネリック型にも適用されます。

class className<T extends TypeA>{
    //...
}
Code language: TypeScript (typescript)

クラスに型パラメータを配置することで、同じ型で動作するメソッドとプロパティを開発できます。

TypeScript ジェネリッククラスの例

この例では、ジェネリックな `Stack` クラスを開発します。

スタックは、後入れ先出し (LIFO) の原則で動作するデータ構造です。つまり、スタックに最初に配置した要素が、スタックから取得できる最後の要素になります。

通常、スタックにはサイズがあります。デフォルトでは空です。スタックには2つの主要な操作があります。

  • Push: スタックに要素を追加します。
  • Pop: スタックから要素を取り出します。

`Stack<T>` と呼ばれる完全なジェネリックStackクラスを以下に示します。

class Stack<T> {
    private elements: T[] = [];

    constructor(private size: number) {
    }
    isEmpty(): boolean {
        return this.elements.length === 0;
    }
    isFull(): boolean {
        return this.elements.length === this.size;
    }
    push(element: T): void {
        if (this.elements.length === this.size) {
            throw new Error('The stack is overflow!');
        }
        this.elements.push(element);

    }
    pop(): T {
        if (this.elements.length == 0) {
            throw new Error('The stack is empty!');
        }
        return this.elements.pop();
    }
}
Code language: TypeScript (typescript)

これは数値の新しいスタックを作成します。

let numbers = new Stack<number>(5);Code language: TypeScript (typescript)

この関数は、2つの数値 `low` と `high` の間の乱数を返します。

function randBetween(low: number, high: number): number {
    return Math.floor(Math.random() * (high - low + 1) + low);
}
Code language: TypeScript (typescript)

これで、`randBetween()` 関数を使用して、`numbers` スタックにプッシュする乱数を生成できます。

let numbers = new Stack<number>(5);

while (!numbers.isFull()) {
    let n = randBetween(1, 10);
    console.log(`Push ${n} into the stack.`)
    numbers.push(n);
}Code language: TypeScript (typescript)

出力

Push 3 into the stack.
Push 2 into the stack. 
Push 1 into the stack. 
Push 8 into the stack. 
Push 9 into the stack. Code language: TypeScript (typescript)

スタックが空になるまで要素をポップする方法は次のとおりです。

while (!numbers.isEmpty()) {
    let n = numbers.pop();
    console.log(`Pop ${n} from the stack.`);
}Code language: TypeScript (typescript)

出力

Pop 9 from the stack.
Pop 8 from the stack.
Pop 1 from the stack.
Pop 2 from the stack.
Pop 3 from the stack.
Code language: TypeScript (typescript)

同様に、文字列のスタックを作成することもできます。例えば

let words = 'The quick brown fox jumps over the lazy dog'.split(' ');

let wordStack = new Stack<string>(words.length);

// push words into the stack
words.forEach(word => wordStack.push(word));

// pop words from the stack
while (!wordStack.isEmpty()) {
    console.log(wordStack.pop());
}
Code language: TypeScript (typescript)

動作の仕組み

  • まず、文を単語に分割します。
  • 次に、`words` 配列内の単語の数と等しいサイズのスタックを作成します。
  • 次に、`words` 配列の要素をスタックにプッシュします。
  • 最後に、スタックが空になるまで単語をポップします。

このチュートリアルでは、TypeScript でジェネリッククラスを開発する方法を学習しました。

このチュートリアルは役に立ちましたか?