0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ジェネリック型

Posted at

ジェネリック型は型定義するための機能である。既存の型を変換して新たな型を作るときに便利。
(例)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;
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?