我有一个服务器端数据加载程序,它从数据模型中检索用户ID,然后在这里检查用户ID是否确实存在:
export const loader = async ({ request, params }: LoaderArgs) => {
const REQUESTED_USER = await GetUserById(Number(params.id))
if (!REQUESTED_USER) {
/**
* If the provided url params user ID does not exist, we will handle it here
*/
return redirectWithError({
request,
message: `User ID: ${params.id} was not found; please enter a valid User ID`,
logMessage: `User ID: ${params.id} was not found; please enter a valid User ID`,
redirectTo: '/manager'
})
}
}
REQUESTED_USER返回:
const REQUESTED_USER: {
id: number;
company_name: string | null;
avatar: string | null;
brand: string | null;
email: string;
name: string | null;
favicon: string | null;
} | null
在该块之后有代码执行一些数据操作,然后在一个类型化的JSON响应中返回数据:
if (GET_SELECTED_SERVICES) {
sma = unwrap_sma[0]
edr = unwrap_edr[0]
cma = unwrap_cma[0]
vms = unwrap_vms[0]
}
return typedjson({
sma,
vms,
cma,
edr,
user
})
之后,我将它传递给一个组件,以便在客户端作出反应:
export const ReadUser = ({ }) => {
const LOADER = useTypedLoaderData<typeof loader>();
const [CSRF] = useCSRF()
return (
<main className="flex w-full">
<Form method="post" className="flex w-full">
<input className="hidden" name={'csrf'} value={CSRF} type="text" readOnly />
<Profile SMA={LOADER.sma} EDR={[]} VMS={[]} CMA={[]} />
</Form>
</main>
)
}
但是,Profile
组件上的属性正在抛出此错误:
Property 'sma' does not exist on type 'TypedResponse<never> | TypedJsonResponse<{ sma: TOptions[]; vms: TOptions[]; cma: TOptions[]; edr: TOptions[]; user: { id: number; company_name: string | null; ... 4 more ...; favicon: string | null; }; }>'.
Property 'sma' does not exist on type 'TypedResponse<never>'.ts(2339)
我已经确定这是因为服务器端REQUESTED_USER
函数中的初始loader
保护,因此LOADER
响应永远不会实现。我猜是吧?这是因为打字稿不理解要求的履行情况,而不是100%的理解(如果有人能解释的话)。
否则,我该如何解决这个问题呢?
LOADER
控件在ReadUser
组件中的类型是:
const LOADER: TypedResponse<never> | TypedJsonResponse<{
sma: TOptions[];
vms: TOptions[];
cma: TOptions[];
edr: TOptions[];
user: {
id: number;
company_name: string | null;
... 4 more ...;
favicon: string | null;
};
}>
我确实尝试过将!REQUESTED_USER
参数更改为REQUESTED_USER === null
,但这并没有改变任何事情。
发布于 2022-11-18 17:09:51
我假设您的加载程序可以返回类型A = {x:1}
和B = {y:2}
,这将导致typeof loader
的联合A | B
类型。如果您尝试访问LOADER.x
,ts会抱怨,因为LOADER
可以是B
类型,而且上面没有属性x
,相反的情况也是如此。
由于类型是根据实际返回的内容正确推断的,并且没有很好的方法来区分联合或个案,因此只能手动分配类型useTypedLoaderData() as A
或抛出重定向,这将从联合中删除第一个返回类型,并且似乎也适用于混合- throw redirect('/somewhere')
。
https://stackoverflow.com/questions/74478656
复制相似问题