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

    配列をフィルターする型

    TypeScriptの型も、配列のようにフィルターしたい。

    type Item = {
      key: string
      disabled?: true
    }
    
    const items = [
      { key: 'foo' },
      { key: 'bar' },
      { key: 'baz', disabled: true },
    ] as const satisfies readonly Item[]
    
    const enabledItems = items.filter(a => !a.disabled).map(a => a.key)

    上記のJavaScriptのコードをTypeで表現すると以下の通り

    type SortKey<T extends readonly Item[]> = {
      [K in keyof T]: T[K]['disabled'] extends true
        ? never
        : T[K]['key']
    }[number]
    
    type EnableItem = SortKey<typeof items>
    //   ^? type EnableItem = 'foo' | 'bar'