2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript入門】型エイリアスとは

Last updated at Posted at 2021-08-28

 型エイリアスで型定義を再利用しよう

 型エイリアスとは

  • typeを使って、型に名前をつけて宣言できる
  • 同じ型を何度も定義する必要がない(再利用ができる)
  • 型に名前をつけることで変数の役割を明確化
/src/object/alias.ts
type Country = {
    capital: string
    language: string
    name: string
  }

  const japan: Country = {
    capital: 'Tokyo',
    language: 'Japanese',
    name: 'Japan',
  }
  console.log('sample 1:', japan)
//sample 1: {capital: "Tokyo", language: "Japanese", name: "Japan"}

  const america: Country = {
    capital: 'Washington, D.C.',
    language: 'English',
    name: 'United States of America',
  }
  console.log('sample 2:', america)
//sample 2: {capital: "Washington, D.C.", language: "English", name: "United States of America"}

合併型(union)と交差型(intersection)

  • 合併型: 型Aか型Bどちらかの型をもつ
  • 交差型: 型Aと型B両方の型を持つ
  • 交差型は「AとBに共通する型」ではない
 // 合併型(union)と交差型(intersection)
  type Knight = {
    hp: number
    sp: number
    weapon: string
    swordSkill: string
  }

  type Wizard = {
    hp: number
    mp: number
    weapon: string
    magicSkill: string
  }

  type Adventurer = Knight | Wizard // 合併型: KnightとWizardどちらかの型を持つ
  type Paladin = Knight & Wizard // 交差型: KnightとWizardが持つ型を全て持っている

  // Knightの型を持つadventurer2
  const adventurer1: Adventurer = {
    hp: 100,
    sp: 30,
    weapon: '木の剣',
    swordSkill: '三連斬り',
  }

  console.log('sample 3:', adventurer1)
//sample 3: {hp: 100, sp: 30, weapon: "木の剣", swordSkill: "三連斬り"}

  // Wizardの型を持つadventurer2
  const adventurer2: Adventurer = {
    hp: 100,
    mp: 30,
    weapon: '木の杖',
    magicSkill: 'ファイヤ',
//sp:30 エラーにならず、動いてしまう。
  }

  console.log('sample 4:', adventurer2)
//sample 4: {hp: 100, mp: 30, weapon: "木の杖", magicSkill: "ファイヤ"}

  // KnightとWizard両方の型を持つpaladin
  const paladin: Paladin = {
    hp: 300,// 1つでもプロパティが欠けるとエラーになる
    sp: 100,
    mp: 100,
    weapon: '銀の剣',
    swordSkill: '三連斬り',
    magicSkill: 'ファイヤボール',
  }

  console.log('sample 5:', paladin)
//sample 5: {hp: 300, sp: 100, mp: 100, weapon: "銀の剣", swordSkill: "三連斬り", …}

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?