LoginSignup
0
0

[Typescript] 型エイリアスってなんぞ?

Posted at

型エイリアスについての簡単な説明

type文を用いて型に名前を付けられる機能のことを型エイリアスと呼びます。

型エイリアスの利点

①コードの可読性向上

使用しない場合


function calculateTotalPrice(cart: { items: { name: string; price: number }[] }) {
  let total = 0;
  for (const item of cart.items) {
    total += item.price;
  }
  return total;
}

使用した場合

type CartItem = {
  name: string;
  price: number;
};

type ShoppingCart = {
  items: CartItem[];
};

function calculateTotalPrice(cart: ShoppingCart) {
  let total = 0;
  for (const item of cart.items) {
    total += item.price;
  }
  return total;
}

CartItemとShoppingCartという型エイリアスを使用することで、calculateTotalPriceの引数の構造が明確になったと思います。

②再利用性の向上

CartItemとShoppingCartの型を作成したことで、他の場所でも利用できるようになりました。変更が必要になった場合は一箇所修正するだけでよくなります!便利!!

0
0
0

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