我正在实现一个 React Router,需要将一些参数从 url 路径传递给函数。
我的函数需要以下类型的参数:
interface PathParams {
appTypeId: string | null
submissionId: string | null
}
async function getSubmission(params: PathParams) {
const submissionExists = await getSubmissionExists(params)
return submissionExists
}
在我的路由器的实现中。我按照 React Router 文档的建议传递参数。
const router = createBrowserRouter([
{
path: '/',
element: <AppLayout />,
id: 'root',
loader: () => defaulNewAPIs(),
children: [
{
index: true,
element: <ReferralDetails status="new" />,
path: '/:appTypeId?/:submissionId?',
loader: ({ params }) => getSubmission(params),
},
],
},
])
我遇到的问题是我传递给函数的 params 对象。 错误如下:
Argument of type 'Params<string>' is not assignable to parameter of type 'PathParams'.
Type 'Params<string>' is missing the following properties from type 'PathParams': appTypeId, submissionId
我不太确定如何解决此错误。
params 仅扩展
string
类型并且实际上是可选的。它们不可为空。
/** * The parameters that were parsed from the URL path. */ export type Params<Key extends string = string> = { readonly [key in Key]: string | undefined; };
interface PathParams {
appTypeId?: string;
submissionId?: string;
}
async function getSubmission(params: PathParams) {
const submissionExists = await getSubmissionExists(params)
return submissionExists
}