ジェネリクスとは
ジェネリクスを使うと、型をパラメータとして受け取る柔軟なコードが書けます。
function identity<T>(arg: T): T {
return arg;
}
const result = identity<string>("hello");ジェネリック型
interface Box<T> {
value: T;
}
const stringBox: Box<string> = { value: "hello" };
const numberBox: Box<number> = { value: 42 };制約付きジェネリクス
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): void {
console.log(arg.length);
}