ジェネリック型は型定義するための機能である。既存の型を変換して新たな型を作るときに便利。
(例)LatestInvoiceという既存の型を定義する。そこから'amount'の型をnumberに変換したLatestInvoiceRawという新たな型を定義し利用するコードは以下のようになる。
interface LatestInvoice {
id: string;
customerId: string;
dueDate: Date;
items: InvoiceItem[];
}
export type LatestInvoiceRaw = Omit<LatestInvoice, 'amount'> & {
amount: number;
};
const invoice: LatestInvoice = {
id: '12345',
customerId: 'ABC123',
dueDate: new Date('2024-04-17'),
items: [
{
description: 'Product A',
quantity: 1,
unitPrice: 100,
},
{
description: 'Product B',
quantity: 2,
unitPrice: 200,
},
],
};
const invoiceRaw: LatestInvoiceRaw = {
id: invoice.id,
customerId: invoice.customerId,
dueDate: invoice.dueDate,
items: invoice.items,
amount: calculateInvoiceAmount(invoice),
};
function calculateInvoiceAmount(invoice: LatestInvoice): number {
let total = 0;
for (const item of invoice.items) {
total += item.quantity * item.unitPrice;
}
return total;
}