LoginSignup
0
0
お題は不問!Qiita Engineer Festa 2023で記事投稿!

[React×TypeScript]propsでデータを渡す際の型定義について

Last updated at Posted at 2023-07-21

はじめに

propsでコンポーネントにデータを渡す際の型定義のテクニックについて書いていきます。

型定義について

コードを書いていきます。

page.tsx
type text = {
    name: string;
    age: number;
}
  
return (
    <>
      <Practice name={"hukuryo"} age={25}/>
    </>
)

まずは、親コンポーネントであるpage.tsxでpropsで送るデータの型を決めます。
そして、子コンポーネントであるPractice.tsxにpropsを渡します。
この時に、nameはstring型に、ageはnumber型に設定してるので、それ以外の型のを渡そうとすると、以下のようにエラーになります。
スクリーンショット 2023-07-21 20.57.39.png

/components/Practice.tsx
type practiceText = {
    name: string;
    age: number;
}

export function Practice(props: practiceText) {
    const { name, age } = props;
    return(
        <div className="text-center mt-10">
            <h1 className="mb-10">Practice props</h1>
            <h4 className="font-bold mb-5">名前{name}</h4>
            <p></p>
            <h4 className="font-bold">年齢{age}</h4>
            <p></p>
        </div>
    )
}

データを受け取った子コンポーネント側では、以下のコードで、親コンポーネントと同じように型定義を行います。

type practiceText = {
    name: string;
    age: number;
}

そして、受け取ったpropsに対して、型を定義します。

export function Practice(props: practiceText) 

例えば、以下のように違った型を定義すると、親コンポーネントでエラーになります。
スクリーンショット 2023-07-21 21.08.25.png

まとめ

このように、TypeSciptを使って、propsで渡すデータに型を定義するのは、安全に値を渡すことができるようにして、バグのリスクを減らしたり、開発効率の向上が期待できるのです。

最後に

他にも記事を書いているので、良ければ見ていってください。

基本設計について
Vue.jsとNode.jsでチャットアプリを作った
Next.js×TypeScriptでTODOアプリを作成する

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