Open3

学び:TypeScript

kouichi.hoshikouichi.hoshi

インターセクション型を使ってみる

実装を進めるにつれて、型定義が膨らみ共通箇所が出現したので、

type TaskProps = {
  id: string
  created_at: Date | null
  is_completed: boolean
  title: string
}

type TaskItemProps = {
  task: TaskProps
  toggleTaskCompletion: TaskAction
  deleteTask: (taskId: string) => void
  updateTask: (taskId: string, newTitle: string) => void
}

type TaskListProps = {
  tasks: TaskProps[]
  toggleTaskCompletion: TaskAction
  deleteTask: (taskId: string) => void
  updateTask: (taskId: string, newTitle: string) => void
}

インターセクション型でまとめることができた!

// タスクに関するプロパティ
type TaskProps = {
  id: string
  created_at: Date | null
  is_completed: boolean
  title: string
}

// タスクに対するアクション(共通化した部分)
type TaskActionsProps = {
  toggleTaskCompletion: TaskAction
  deleteTask: (taskId: string) => void
  updateTask: (taskId: string, newTitle: string) => void
}

// 個別のタスクアイテム用の型
type TaskItemProps = TaskActionsProps & {
  task: TaskProps
}

// 複数のタスクリスト用の型
type TaskListProps = TaskActionsProps & {
  tasks: TaskProps[]
}

// TaskAction の型定義
type TaskAction = (taskId: string, isCompleted: boolean) => void

インターセクション型 (intersection type) | TypeScript入門『サバイバルTypeScript』

kouichi.hoshikouichi.hoshi

型注釈 JSX.Element

以下のようなJSXを含むオブジェクトの型定義をしてみる。

const animals = [
  {
    name: 'パンダ',
    classification: '哺乳類',
    habitat: '竹林',
    conservationStatus: '絶滅危惧種',
    description: '竹を主食とする。',
  },
  {
    name: 'ペンギン',
    classification: '鳥類',
    habitat: '南極',
    conservationStatus: '低危険種',
    description: (
      <>
        水中での泳ぎが得意。
        <br />
        飛ぶことはできない。
      </>
    ),
  },
  {
    name: 'カクレクマノミ',
    classification: '魚類',
    habitat: 'サンゴ礁',
    conservationStatus: '低危険種',
    description: (
      <a href='https://example.com/clownfish' target='_blank'>
        イソギンチャクと共生する小型の魚。
      </a>
    ),
  },
];

テーブルタグの中身として出力するコンポーネントの例。
Next.jsではpropsでhtmlを渡すと文字列になるので、htmlとして表示させたいときはJSXを使う。(セキュリティに注意)

type AnimalItemProps = {
  name: string;
  classification: string;
  habitat: string;
  conservationStatus: string;
  description: string | JSX.Element; //文字列またはJSXを受け取る
};

type AnimalRowProps = {
  animalItem: AnimalItemProps;
};

const AnimalRow = ({ animalItem }: AnimalRowProps): JSX.Element => {
  const { name, classification, habitat, conservationStatus, description } = animalItem;

  return (
    <tr>
      <td>{name}</td>
      <td>{classification}</td>
      <td>{habitat}</td>
      <td>{conservationStatus}</td>
      <td>{description}</td>
    </tr>
  );
};
kouichi.hoshikouichi.hoshi

メモ:ドキュメンテーションコメント

エディタで
/** 見出しのタイトル */
のように書くと、
カーソルをあわせたときにコメントがポップアップで表示される。


見出しのタイトルがポップアップされている

type PageHeaderProps = {
  /** 見出しのタイトル */
  title: string
  /** サブタイトル(オプション) */
  subTitle?: string
  /** 外側のコンテナのクラス名(オプション) */
  outerClassName?: string
  /** タイトルのクラス名(オプション) */
  className?: string
  /** サブタイトルのクラス名(オプション) */
  subTitleClassName?: string
  /** 見出しレベルを指定(オプション) */
  tag?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'
}