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

ダイナミックルート作成時にTypeScriptの型エラーでハマった話

Posted at

ダイナミックルート作成時にTypeScriptの型エラーにハマった話

TypeScriptで BlogProp という型を定義しようとしたとき、思わぬ型エラーにハマったので備忘録として残しておく。

やりたかったこと

Next.jsの PageProps に合わせて、params というプロパティを持つ BlogProp 型を定義しようとした。

type BlogProp = { params: { slug: string } };

しかし、これを使おうとすると以下のエラーが発生。

発生したエラー

Type error: Type 'BlogProp' does not satisfy the constraint 'PageProps'.
  Types of property 'params' are incompatible.
    Type '{ slug: string; }' is missing the following properties from type 'Promise<any>': then, catch, finally, [Symbol.toStringTag]

params{ slug: string } を渡したつもりだったが、Promise<any> が期待されているらしい。
つまり、params は同期的なオブジェクトではなく、非同期の Promise として扱う必要がある。

解決策

params の型を Promise<{ slug: string }> に変更することでエラーを解消できた。

type BlogProp = { params: Promise<{ slug: string }> };

これで params を非同期で取得する前提の型となり、期待される Promise 型と一致する。
最初は「えっ、なんで Promise になるの?」と戸惑ったが、Next.jsの PageProps の仕様を考えると納得。
同じエラーでハマる人がいたら、参考になれば嬉しい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?