≪ Today I learned.
RSS購読
    公開日
    タグ
    TypeScript
    著者
    ダーシノ

    存在しない型をつくらない

    不要な状態ができないような型を作るアプローチは良い、古事記にもそう書かれている。

    Bad

    Optional Propertyをつかって複数の型をひとつにまとめているため、不要な状態ができてしまう。

    type Item = {
      type: 'a' | 'b'
      a?: string
      b?: number
    }
    
    // 存在しない状態
    const a: Item = {
      type: 'a',
      a: 'xxxx',
      b: 9999
    }
    const b: Item = {
      type: 'b',
    }

    Good

    存在する型のみを定義し、Union Typeで複数の状態を表現する。

    type A = {
      type: 'a'
      a: string
    }
    type B = {
      type: 'b'
      b: number
    }
    type Item = A | B