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

如何让TypeScript中useSWR的返回数据仅为指定类型而非undefined?

解决useSWR返回data为MyInterface | undefined的问题

核心原因

即便设置了fallbackData,useSWR的默认类型定义仍会保留undefined的可能性——这是因为fetcher可能抛出错误、请求失败,或者你传入的fallbackData本身不符合MyInterface的完整结构(比如你当前用的{},如果MyInterface有必填字段,这个对象是不合法的)。

具体解决方案

1. 确保fallbackData符合MyInterface完整结构

首先要补全fallbackData的所有必填属性,让它真正满足MyInterface类型:

// 先定义符合MyInterface的默认数据
const defaultMyData: MyInterface = {
  // 这里补全MyInterface的所有必填字段,比如:
  id: 'default-id',
  title: '默认标题'
};

const { data } = useSWR<MyInterface>(
  'myendpoint',
  fetcher,
  { fallbackData: defaultMyData }
);

2. 使用非空断言强制类型

如果你能确保无论请求成功与否,data都不会是undefined(有fallbackData兜底),可以直接用非空断言!来去除undefined类型:

const { data } = useSWR<MyInterface>(
  'myendpoint',
  fetcher,
  { fallbackData: defaultMyData }
);

// 使用data时添加断言
console.log(data!.id);

3. 类型断言返回结果

直接对useSWR的返回值做类型断言,明确data为MyInterface:

const { data } = useSWR<MyInterface>(
  'myendpoint',
  fetcher,
  { fallbackData: defaultMyData }
) as { data: MyInterface };

4. 约束fetcher的返回类型

确保你的fetcher函数明确返回Promise<MyInterface>,而不是Promise<MyInterface | undefined>,这会让useSWR的类型推断更准确:

// 定义fetcher时指定返回类型
const fetcher = async (url: string): Promise<MyInterface> => {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('请求失败');
  }
  return response.json();
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:55:31