1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ライブラリの型エラー解決手順:NextUIのDatePickerを例に解説

Posted at

はじめに

TypeScriptを使用しているプロジェクトでは、依存関係のバージョン不一致が原因で型エラーが発生することがあります。

本記事では、NextUIのDatePickerで発生した型エラーを例に、一般的な型エラーの解決手順を解説します。

発生した型エラー

NextUIのDatePickerコンポーネントを使用する際に、以下のような型エラーが発生しました。

Type 'ZonedDateTime | null' is not assignable to type 'CalendarDate | CalendarDateTime | ZonedDateTime | null'.
  Type 'ZonedDateTime' is not assignable to type 'CalendarDate | CalendarDateTime | ZonedDateTime | null'.
    Type 'import("/path/to/node_modules/@internationalized/date/dist/types").ZonedDateTime' is not assignable to type 'import("/path/to/node_modules/@nextui-org/system/node_modules/@internationalized/date/dist/types").ZonedDateTime'.
      Property '#private' in type 'ZonedDateTime' refers to a different member that cannot be accessed from within type 'ZonedDateTime'.

これは、同じライブラリ (@internationalized/date) でありながら異なる場所からインポートされていることが原因で、TypeScriptが異なる型として扱ってしまうために発生しています。

型エラーの原因

この問題の原因を特定するために、依存関係のバージョンを調査しました。

特に注目したのは、以下の2つの異なる @internationalized/date のインポートパスです。

  1. プロジェクトが直接使用している @internationalized/date
  2. NextUIが内部で使用している @internationalized/date

これらのバージョンが異なる場合、TypeScriptは ZonedDateTime を異なる型と見なし、型の不一致が発生することがわかりました。

型エラー解決の手順

この型エラーを解決するために行った手順を以下にまとめます。

1. エラーメッセージの分析

まず、エラーメッセージを読み取り、どの型が競合しているかを特定します。

今回の場合、@internationalized/date が異なるパスからインポートされていることが問題の核心でした。

2. 依存関係のバージョンを確認

依存関係のバージョンを確認するために、yarn.lock を調査しました。

以下のコマンドを実行し、NextUIが使用している @internationalized/date のバージョンを特定しました。

grep -A 10 "@internationalized/date" yarn.lock
結果
"@nextui-org/datepicker@npm:2.2.9":
  version: 2.2.9
  resolution: "@nextui-org/datepicker@npm:2.2.9"
  dependencies:
    "@internationalized/date": "npm:3.6.0" # ここ
    "@react-aria/datepicker": "npm:3.12.0"

その結果、NextUIの DatePicker が @internationalized/date のバージョン 3.6.0 に依存していることが分かりました。

3. 主要ライブラリに合わせてバージョンを統一

NextUIが使用しているバージョン (3.6.0) に合わせて、プロジェクトの package.json に明示的に追加しました。

{
  "dependencies": {
    "@internationalized/date": "3.6.0",
  }
}

これにより、NextUIとプロジェクトが同じバージョンの @internationalized/date を使用するようになります。

4. 依存関係を再インストール

変更後に、以下のコマンドで依存関係を再インストールしました。

yarn install --mode update-lockfile

これにより、依存関係が正しく統一され、型エラーが解消されました。

まとめ

TypeScriptプロジェクトで発生する型エラーは、一見複雑に見えても、落ち着いてエラーを読み、1つずつ原因を追求していくことで解決できることを体感しました。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?