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

TypeScript无法正确推断异步函数的Awaited返回类型问题

问题分析与解决方案

核心原因

你给props变量显式标注了Props类型,这会让TypeScript优先使用这个显式声明的类型,而非函数实际实现的返回类型。虽然hover函数时能看到TS识别出了函数的真实返回类型,但typeof props取的是你标注的Props类型——如果Props被定义成了宽泛的(args: any) => Promise<{}>或类似结构,ReturnType<typeof props>自然会推断出Promise<{}>,最终Awaited处理后就是{},导致组件中无法识别id和name属性。

解决方案

方案1:移除显式的Props标注

让TypeScript自动推断函数的完整类型,这样typeof props会指向函数的真实实现类型,后续的ReturnType和Awaited就能正确提取返回对象的类型:

export const props = async ({ groups }) => {
  return {
    id: 123,
    name: groups.name,
  };
};

type InferredProps = Awaited<ReturnType<typeof props>>;

export const component: FC<InferredProps> = ({ id, name }) => {
// ...
};

方案2:保留Props标注但对齐类型

如果必须保留Props类型声明,可以先定义函数实现,再基于实现类型推导Props,确保类型对齐:

// 先写函数实现,让TS自动推断类型
const propsImpl = async ({ groups }) => {
  return {
    id: 123,
    name: groups.name,
  };
};

// 基于实现推导Props类型
type Props = typeof propsImpl;
export const props: Props = propsImpl;

type InferredProps = Awaited<ReturnType<typeof props>>;

export const component: FC<InferredProps> = ({ id, name }) => {
// ...
};

方案3:修正Props的定义

如果Props是外部定义的类型,需要确保它的返回类型是具体的,而非宽泛的Promise<{}>。比如调整Props的定义为:

type Props = (args: { groups: URLPatternComponentResult["groups"] }) => Promise<{
  id: number;
  name: string | undefined;
}>;

这样ReturnType<typeof props>就能正确拿到对应的Promise返回类型,Awaited处理后也会得到预期的对象类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:25:53