You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Remix中如何为json()包裹的异步函数显式指定返回类型?

在Remix中为json()包裹的异步函数显式声明返回类型

直接上正确写法:你需要把返回类型声明为Promise<TypedResponse<T[]>>,因为Remix的json()函数返回的是TypedResponse类型(它是Remix对Response的封装,携带了你的数据类型)。

示例代码:

import { json, TypedResponse } from "@remix-run/node"; // 根据你的运行环境调整导入路径,比如@remix-run/cloudflare等

async function fetchData(): Promise<TypedResponse<YourDataType[]>> {
  const data: YourDataType[] = await fetchSomeData(); // 你的数据获取逻辑
  return json(data);
}

为什么你之前的写法都错了?

  • 第一种Promise<T[]>:json()返回的不是原始的数组对象,而是包装后的TypedResponse实例,所以原始数据类型和返回值类型不匹配。
  • 第二种Promise<JsonFunction>:JsonFunction是json这个函数本身的类型,不是它调用后返回值的类型,完全不沾边。
  • 第三种Promise<T[] & JsonFunction>:把数据类型和函数类型强行交叉,完全不符合json()的返回结构,必然报错。
  • 第四种Promise<typeof json> & { object: T[] }:同样混淆了函数本身的类型和返回值的结构,逻辑错误。

简化写法(可选)

如果觉得TypedResponse写起来麻烦,可以自定义类型别名:

import { TypedResponse } from "@remix-run/node";

type JsonRes<T> = TypedResponse<T>;

async function fetchData(): Promise<JsonRes<YourDataType[]>> {
  return json(await fetchSomeData());
}

内容的提问来源于stack exchange,提问作者ngeksdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 20:32:07