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

如何让TypeScript函数根据参数返回对应Resume接口的数组类型?

问题

现有用于构建简历的分段接口IWorkExperience、IEducation,以及整合这些分段的IResume接口,需要实现getSectionDataByType函数,使其根据传入的类型参数返回对应接口的数组类型,当前函数返回any[]不符合预期。相关代码如下:

export interface IWorkExperience {
  unique: string;
  jobTitle: string | null;
  company: string | null;
  city: string | null;
  country: string | null;
  from: string | null;
  to: string | null;
  description: string | null;
  position: number;
  height: number;
}

export interface IEducation {
  unique: string;
  school: string | null;
  field: string | null;
  degree: string | null;
  city: string | null;
  country: string | null;
  from: string | null;
  to: string | null;
  current: boolean;
  description: string | null;
  position: number;
  height: number;
}
export interface IResume {
  workExperiences: IWorkExperience[];
  educations: IEducation[];
}

export const getSectionDataByType = (type: string, resume: IResume): any[] => {
  let section: any;

  Object.keys(resume).map((k, i) => {
    if (k === type) {
      section = resume[k as keyof typeof resume];
    }
  });

  return section;
}

请问如何修改该函数,使其正确返回IWorkExperience[]或IEducation[]类型?

解决方案

可以通过限制参数类型为IResume的键名,并利用类型推断让函数返回对应类型的数组,同时简化冗余的遍历逻辑。修改后的代码如下:

export interface IWorkExperience {
  unique: string;
  jobTitle: string | null;
  company: string | null;
  city: string | null;
  country: string | null;
  from: string | null;
  to: string | null;
  description: string | null;
  position: number;
  height: number;
}

export interface IEducation {
  unique: string;
  school: string | null;
  field: string | null;
  degree: string | null;
  city: string | null;
  country: string | null;
  from: string | null;
  to: string | null;
  current: boolean;
  description: string | null;
  position: number;
  height: number;
}
export interface IResume {
  workExperiences: IWorkExperience[];
  educations: IEducation[];
}

// 修改后的函数
export const getSectionDataByType = <T extends keyof IResume>(type: T, resume: IResume): IResume[T] => {
  return resume[type];
}

关键修改说明:

  • 泛型约束参数:用T extends keyof IResume限制type只能传入IResume中存在的键名(即"workExperiences"或"educations"),避免无效输入。
  • 自动推断返回类型:返回类型指定为IResume[T],TypeScript会根据传入的type自动匹配对应的数组类型,无需手动标注。
  • 简化逻辑:直接通过键名访问resume的属性,去掉不必要的遍历操作,代码更高效简洁。

使用示例:

const resume: IResume = {
  workExperiences: [],
  educations: []
};

// 自动推断返回IWorkExperience[]类型
const workData = getSectionDataByType("workExperiences", resume);
// 自动推断返回IEducation[]类型
const eduData = getSectionDataByType("educations", resume);

内容的提问来源于stack exchange,提问作者Burak Emre Kadan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:40:10