はなゐろぐ

主に技術関係の覚え書きです。

Astroで継承元レイアウトの型を拡張する

2025年3月24日

Base.astro(親レイアウト)から下層ページ用レイアウトLower.astro(子レイアウト)を作成し、親のPropsに子のPropsをマージします。

まず、親レイアウトのPropsがこうだったとします。

Base.astro
---
export interface Props {
  title?: string
  description?: string
  ogp?: {
    type?: string
    image?: string
    url?: string
  }
}
---

次に、Astroの型ユーティリティComponentProps型を使って、子レイアウトから親レイアウトのPropsを参照します。

TypeScript
Astro組み込みのTypeScriptサポートの使い方を学ぶ。
TypeScript favicon https://docs.astro.build/ja/guides/typescript/#componentprops型
TypeScript

あとは、子レイアウト側で型を継承してhogeを追加して完了です。こうすることで、子レイアウトで親レイアウトも含めたPropsの補完がきくようになります。

Lower.astro
---
import type { ComponentProps } from 'astro/types'
import Layout from '@/layouts/Base.astro'

type BaseProps = ComponentProps<typeof Layout>
export interface Props extends BaseProps {
  hoge?: string
}
---