如何将从 Remix 的 useLoaderData<T> 返回的 JsonifyObject<typeof loader> 传递给函数

问题描述 投票:0回答:1

从下面的 Remix 2.9.2 路线代码中,我收到 TypeScript 错误...

JsonifyObject<IdAndDate>
”类型的参数不可分配给“
IdAndDate
”类型的参数。

...我不知道如何导入 JsonifyObject。

import { useLoaderData } from "@remix-run/react";

type IdAndDate = {
  id: number;
  date: Date;
};

export default function Component() {
  //
  const idAndDate = useLoaderData<typeof loader>();
  // this line would work great, and helpfully, idAndDate.date is typed as string because it was serialized...
  //return (<div>{idAndDate.id}: {idAndDate.date}</div>);

  // but this, doesn't work because --
  // "Argument of type 'JsonifyObject<IdAndDate>' is not assignable to parameter of type 'IdAndDate'."
  // -- which is true, but I can't figure out how to import JsonifyObject :\
  return <div>{formatIdAndDate(idAndDate)}</div>;
}

export function loader(): IdAndDate {
  return { id: 42, date: new Date() };
}

function formatIdAndDate(idAndDate: IdAndDate): string {
  return `${idAndDate.id}: ${idAndDate.date}`;
}

我尝试过...

import { JsonifyObject } from "@remix-run/server-runtime/dist/jsonify"

...但是出现错误...

模块“@remix-run/server-runtime/dist/jsonify”在本地声明“JsonifyObject”,但未导出。

...这是有道理的,因为它没有导出——但我找不到其他地方可以导入它。

我不想使用

as IdAndDate
,因为这会放弃一个真正有用的事实,即 JsonifyObject 在对象序列化后知道日期是一个字符串。

(另外,我知道这个例子很简单,不需要函数,但这被简化以显示问题的核心。在真实的代码中,有更复杂的逻辑,在浏览器上完成确实有意义侧面。)

我错过了一些简单的事情吗? JsonifyObject 是否导出到其他我找不到的地方?

typescript remix.run
1个回答
0
投票

在您的加载程序中,您应该使用

json
帮助器。

return json({ id: 42, date: new Date() })

然后在您的 UI 组件中,

useLoaderData
将以
JsonifyObject
类型返回您的数据。

© www.soinside.com 2019 - 2024. All rights reserved.