TypeScriptでよくArray<T>の様な記述が出てきます。これはざっくばらんにいえば型定義中に使う変数です。Tの中には string, number などの具体的な型が入ります。例は次です。
// 配列のラッピングクラスCollectionである契約を定義します
interface CollectionContract<T> {
items: Array<T>
all(): Array<T>
push(newItem: T): this
}
// 配列のラッピングクラスCollection実体を定義します
class Collection<T> implements CollectionContract<T> {
constructor(items: Array<T>) {
this.items = items;
}
items: Array<T>;
all(): Array<T> {
return this.items;
}
push(newItem: T): this {
this.items.push(newItem);
return this;
}
}
// 使い方
const numCollection = new Collection([1, 2, 3, 4]);// constructor(Array<T>) = constructor(Array<number>)となる
// numCollection.push('hoge'); // 'hoge'は number でなく string なので、push(newItem: number)に適応できずNG. コンパイルエラー発生
numCollection.push(6); // 6は number なのでOK
const numArray: Array<number> = numCollection.all(); // collectionのallメソッドが返すのはArray<number>なのでOK
const strCollection = new Collection(['a', 'b', 'c', 'd']);// constructor(Array<T>) = constructor(Array<string>)となる
// strCollection.push(2); // 2は string でなく number なので、push(newItem: string)に適応できずNG. コンパイルエラー発生
strCollection.push('fuga'); // 'fuga'は string なのでOK
const strArray: Array<string> = strCollection.all(); // collectionのallメソッドが返すのはArray<string>なのでOK
例の様にクラスのプロパティで共通のなんらかの決まった型の値を持つと定める時に便利です。JavaScriptそのもの, Node.js, Vue, Reactの様な広範な範囲をカバーするフレームワーク等の仕組みでよく使われ、よく型定義ファイルで出てきます。
この型の変数ともいえる仕組みはジェネリクスといいます。ジェネリクスはどの型でもOKという点では any と同じですが、同じ型を指すという点で決定的に異なります。公式の詳しい説明は次にあります。
Generics · TypeScript
Generics – TypeScript Deep Dive 日本語版