[TypeScript]ジェネリック型エイリアス
type Box<T> = { value: T; }; const numberBox: Box<number> = { value: 100 }; const stringBox: Box<string> = { value: "Hello" }; console.log(numberBox.value); // 100 console.log(stringBox.value); // "Hello"
配列
type List<T> = T[]; const numbers: List<number> = [1, 2, 3]; const strings: List<string> = ["a", "b", "c"]; console.log(numbers); // [1, 2, 3] console.log(strings); // ["a", "b", "c"]
オブジェクト型の拡張
type Identifiable<T extends { id: number }> = { data: T; }; const user: Identifiable<{ id: number; name: string }> = { data: { id: 1, name: "Taro" }, }; console.log(user.data.name); // "Taro"
複数の型パラメータ
type Pair<T, U> = { first: T; second: U; }; const pair: Pair<number, string> = { first: 1, second: "One" }; console.log(pair.first); // 1 console.log(pair.second); // "One"
関数
type Func<T, U> = (arg: T) => U; const toString: Func<number, string> = (num) => `Number: ${num}`; console.log(toString(10)); // "Number: 10"
デフォルト型
type ResponseData<T = string> = { data: T; }; const res1: ResponseData = { data: "Success" }; // Tはstringとして扱われる const res2: ResponseData<number> = { data: 200 }; // 明示的にnumberを指定 console.log(res1.data); // "Success" console.log(res2.data); // 200
条件付き型
type IsString<T> = T extends string ? "文字列" : "その他"; type Result1 = IsString<string>; // "文字列" type Result2 = IsString<number>; // "その他" let test1:Result1 = "文字列";//"文字列"以外はエラー let test2:Result2 = "その他";//"その他"以外はエラー console.log(test1); console.log(test2);
型制約
class DataStorage<T extends number | string>{ private items:T[] = []; }