해결된 질문
작성
·
49
0
안녕하세요!
build할 때 계속해서 type 오류가 발생하여 질문 드립니다.
현재 page.tsx에는 아래와 같이 작성되어 있습니다.
import BookItem from "@/components/book-item";
import { BookData } from "@/types";
export default async function Page({
searchParams,
}: {
searchParams: {
q?: string;
};
}) {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_SERVER_URL}/book/search?q=${searchParams.q}`
);
if (!response.ok) {
return <div>오류가 발생했습니다...</div>;
}
const books: BookData[] = await response.json();
return (
<div>
{books.map((book) => (
<BookItem key={book.id} {...book} />
))}
</div>
);
}
근데 여기서 build를 하면 아래와 같은 에러가 발생합니다.
.next/types/app/(with-searchbar)/search/page.ts:34:29
Type error: Type 'Props' does not satisfy the constraint 'PageProps'.
Types of property 'searchParams' are incompatible.
Type 'Record<string, string | string[]> | undefined' is not assignable to type 'Promise<any> | undefined'.
Type 'Record<string, string | string[]>' is missing the following properties from type 'Promise<any>': then, catch, finally, [Symbol.toStringTag]
32 |
33 | // Check the prop type of the entry function
> 34 | checkFields<Diff<PageProps, FirstArg<TEntry['default']>, 'default'>>()
| ^
35 |
36 | // Check the arguments and return type of the generateMetadata function
37 | if ('generateMetadata' in entry) {
Next.js build worker exited with code: 1 and signal: null
사실 gpt를 이용하여 받은 코드로 작성해보면 에러를 해결할 수는 있는데 이게 근본적인 해결 방법인지 잘 모르겠고, gpt가 작성한 코드가 잘 이해가 되지 않습니다.
우선 gpt에서 받은 답변은 아래와 같습니다.
import BookItem from "@/components/book-item";
import { BookData } from "@/types";
export default async function Page({ searchParams }: any) {
const qRaw = searchParams?.q;
const q = Array.isArray(qRaw) ? qRaw[0] : qRaw ?? "";
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_SERVER_URL}/book/search?q=${encodeURIComponent(q)}`
);
if (!response.ok) {
return <div>오류가 발생했습니다...</div>;
}
const books: BookData[] = await response.json();
return (
<div>
{books.map((book) => (
<BookItem key={book.id} {...book} />
))}
</div>
);
}
이렇게 하면 해결은 되긴합니다.
다만 왜 해결이 되는 건지 이해가 잘 되지 않아서 그런데 왜 자꾸 build할 때 type 오류가 발생하는지 알려주시면 감사드리겠습니다!
답변 2
0
안녕하세요 이정환입니다.
오류 메세지를 읽어보시면 searchParams 라는 Props의 타입 정의가 잘못되었다고 나와 있습니다.
이런 오류가 발생하는 이유는 우리 강의의 3.2) 페이지 라우팅 설정하기 의 6분 21초 경에 설명 드리고 있듯이 Next.js 15.1 버전부터는 searchParams와 params의 타입이 모두 Promise로 래핑되어 제공되기 때문입니다. (자세한 내용은 앞서 언급해드린 챕터를 참고하세요!)
이에 해당 내용을 참고하셔서 코드 상에 serachParams와 params의 타입을 모두 Promise로 변경하시면 되겠습니다!
0
안녕하세요, 인프런 AI 인턴입니다. khhan1990님.
Next.js 프로젝트에서 현재 발생하는 타입 오류에 대해 설명드리겠습니다. 위의 문제는 searchParams
의 타입이 잘못 정의되었거나 기존 Next.js 버전 업데이트로 인한 타입 호환성 문제로 발생할 수 있습니다. 최신 Next.js 버전에서는 searchParams
의 타입이 Promise
로 감싸져 제공될 수 있습니다.
타입스크립트 타입 호환성 문제:
searchParams
는 서버 컴포넌트에 Promise
형태로 전달될 수 있습니다.Promise
타입 간의 충돌이 생길 수 있습니다.제안된 해결 방법:
searchParams
의 타입을 Promise
로 명시해야 합니다.searchParams
의 타입을 any
로 사용해 오류를 임시로 해결하는 방식입니다. 그러나 이는 근본적인 타입 안전성을 제공하지 않으므로 적합하지 않을 수 있습니다.타입 정의 수정:
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>;
}) {
const resolvedSearchParams = await searchParams;
const q = Array.isArray(resolvedSearchParams.q) ? resolvedSearchParams.q[0] : resolvedSearchParams.q ?? "";
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_SERVER_URL}/book/search?q=${encodeURIComponent(q)}`
);
if (!response.ok) {
return <div>오류가 발생했습니다...</div>;
}
const books: BookData[] = await response.json();
return (
<div>
{books.map((book) => (
<BookItem key={book.id} {...book} />
))}
</div>
);
}
버전 관련 문제 점검 및 Next.js 사용법 검토:
아래는 비슷한 문제에 대한 기존 답변 링크입니다:
- checkFields
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다. 현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏 추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.
아.. 말씀주신 건 수업 때 들어서 알고 있었습니다만 Promise로 써도 계속해서 오류가 나서 next 버전도 확인하고 저만 Promise를 쓴거에 에러가 나는건가 하고 계속 찾아봤는데 알고보니 구조분해 할당으로 q를 뽑아놓고 사용할 때 {searchParams.q}로 쓰고 있었네요..😓
q의 에러에
Property 'q' does not exist on type 'Promise<{ q?: string | undefined; }>'.ts(2339)
page.tsx(14, 77): Did you forget to use 'await'?
이렇게만 떠서 계속 await에만 초점을 맞춰서 에러를 찾다보니 생각도 못했던 것 같습니다..ㅎㅎ
알려주셔서 감사드립니다!